How to put ' and " into sql

  • Thread starter Thread starter Igor
  • Start date Start date
I

Igor

I need to put " and ' into sql server database.
I write:
string SQL = "INSERT INTO SomeTable (Email, Message) VALUES (' +
txtName.Text + "','" + txtMessage.text +')";

What if someone enters character ' in text box? Than I got error message
because ' is character for strings in sql. Then my sql query have more
fields because of this characters. How can I put ' and " into sql database?
 
You could double quotes but it's better to use parameters so that you don't
have to escape quotes, format properly dates and decimal numbers (for
example if the app runs in a foreign country you could easily insert 2,5
instead of 2.5 in a SQL String etc) plus added security against SQL
injection attacks...

If your DB doesn"t support name parameters you can use ? instead.

Try :
http://aspnet101.com/aspnet101/tutorials.aspx?id=1
 
Igor,

You can always double your quote - just use string.Replace function.
Another way would be to create parametarized query, similar to the following:
string SQL = "insert into someTable (Email, Message) values (@Email,
@Message)";

This way you will not have to wory about quotes, and also quard yourself
against SQL injection attacks
 
Igor said:
I need to put " and ' into sql server database.
I write:
string SQL = "INSERT INTO SomeTable (Email, Message) VALUES (' +
txtName.Text + "','" + txtMessage.text +')";

What if someone enters character ' in text box? Than I got error message
because ' is character for strings in sql. Then my sql query have more
fields because of this characters. How can I put ' and " into sql database?

As everyone already has said, you should use a parameterised query.

If you for some reason choose to format the string yourself, the first
thing you have to do is to find out how to escape the strings properly.
That depends on what database you are using, and if you don't do it
correctly, your application is wide open for sql injections. (That's why
you should use parameters.)

For MS SQL Server and MS Access you encode the string by replacing
apostrophes with double apostrophes.

For MySQL you encode the string by replacing \ with \\ and ' with \', in
that order.
 
Back
Top