How to put ' and " into sql

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?
 
P

Patrice

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
 
G

Guest

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top