1

I'm a newbie in the realm of SQL still, so I have a question about whether I'm using a safe practice.
I have a user table with a column for extra notes, which should be able to contain pretty much anything a person can type in. I'm taking care of (or I think I am) the single quotes in the notes field by doing

notes = notes.replace("'", "''");

Then, the query I will execute is put together like this:

String query = "INSERT into users (username, password, notes) VALUES('" + username + "' , '" + password + "' , '" + notes + "'";

Aside from the password not being encrypted, what else might I be missing here? I'm not expecting that many hackers will even know of the existence of this software, but then again, nobody expects their code to be hacked.

2
  • If you state your platform people can link to the corresponding methods used to generate parameterized queries which take care of escaping values for you as well as generally being more flexible/readable. Commented Nov 14, 2011 at 15:50
  • Sorry, platform is Java, though I just needed to be introduced to the topic of parameterized queries. Commented Nov 14, 2011 at 16:25

3 Answers 3

3

Always use parameterised queries.

Using ASP.NET C#:

SqlCommand cmd = new SqlCommand("INSERT INTO TableA (Username, Password, Notes) VALUES (@Username , @Password, @Notes)", Conn);
cmd.parameters.add("@Username",sqldbtype.nvarchar).value = username;
cmd.parameters.add("@Password",sqldbtype.nvarchar).value = password;
cmd.parameters.add("@Notes",sqldbtype.nvarchar).value = notes;
cmd.executenonquery();

Then you don't need to worry about single quotes, or SQL Injection.

Sign up to request clarification or add additional context in comments.

2 Comments

plus - many servers will be able to cache a plan for a parameterized query and hence will perform quicker.
Thanks! I didn't mention my platform, sorry, but you gave me the answer I needed, even if it is a different platform.
2

Google for "prepared statements" - a secure way to execute queries with users input.

Comments

2

Sorry, I have no privilege to comment just yet, but what I can say will help is to utilize stored procedures, and to use object-oriented style of coding to use parameters.

You can also check this site out as it provides a lot of info on improving your security (which includes the fight against SQL injection): https://www.owasp.org/index.php/Main_Page

1 Comment

+1 for mentioning stored procedures. Concatenating SQL commands is very dangerous.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.