Friday, February 24, 2012

Insert problem with single quotes

I have a problem with inserting a string with single quotes. For instance,

string testme = "we don't have anything";

insert into tableone (buff) values ("'" + testme + "'");

I get an error with the word "don't" with single quote. But if I delete the single quote "dont" then it inserts okay. Is is a bug in sql 2005? Please help. Thanks.

blumonde

blumonde:

I have a problem with inserting a string with single quotes. For instance,

string testme = "we don't have anything";

insert into tableone (buff) values ("'" + testme + "'");

I get an error with the word "don't" with single quote. But if I delete the single quote "dont" then it inserts okay. Is is a bug in sql 2005? Please help. Thanks.


No, it's not a bug with SQL Server 2005. To use that method, you would need to double up any single quotes within the testme string in order to "escape" them so that your INSERT statement works correctly.

However, you should be using parameters to pass UI-supplied values to your SQL statement. Here's the why:

Please, please, please, learn about injection attacks!

And here's the how:
How To: Protect From SQL Injection in ASP.NET
Using Parameterized Query in ASP.NET, Part 1
Using Parameterized Query in ASP.NET, Part 2
Using Parameterized Queries in ASP.Net
|||

tmorton:

blumonde:

I have a problem with inserting a string with single quotes. For instance,

string testme = "we don't have anything";

insert into tableone (buff) values ("'" + testme + "'");

I get an error with the word "don't" with single quote. But if I delete the single quote "dont" then it inserts okay. Is is a bug in sql 2005? Please help. Thanks.


No, it's not a bug with SQL Server 2005. To use that method, you would need to double up any single quotes within the testme string in order to "escape" them so that your INSERT statement works correctly.

However, you should be using parameters to pass UI-supplied values to your SQL statement. Here's the why:

Please, please, please, learn about injection attacks!

And here's the how:
How To: Protect From SQL Injection in ASP.NET
Using Parameterized Query in ASP.NET, Part 1
Using Parameterized Query in ASP.NET, Part 2
Using Parameterized Queries in ASP.Net

Thank you Tmorton. I think parameters will have solved the problem.

blumonde

No comments:

Post a Comment