Indigenuity
Indigenuity

Reputation: 9740

Making sql insert statement safe

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.

Upvotes: 1

Views: 2820

Answers (3)

Nonym
Nonym

Reputation: 6299

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

Upvotes: 2

Eugene
Eugene

Reputation: 3375

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

Upvotes: 2

Curtis
Curtis

Reputation: 103358

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.

Upvotes: 3

Related Questions