tags:

views:

567

answers:

4

Hi, I know I can use the parameters, but what is the right way to escape string sequences? The query could be like this:

"INSERT INTO records (ReferenceID,Name,Note,Author) VALUES ('" + ID+ "','" + addlevel.textBox1.Text + "','"+addlevel.textBox2_note.Text+ "','"+Program.Username+"')";

I am ONLY curious, just want to know :)

EDIT: But what about that? "CREATE TABLE "+string" .... parameters cannot be used here!

+5  A: 

The right way is to use parameters.

"Just Say No" to trying to do the escaping yourself - it's far too easy to get wrong. Why do you think you'd want to escape them manually instead of using parameters?

Jon Skeet
Absolutely right - parameters win on every count.
David M
I know, I am jus curious. BTW, I have edited the question. What if user enters table name? Then I cannot use parameters either.
Snake
You wouldn't want to let users define the table they are inserting to, that would lead to a very large security hole.
Paolo
A: 

If you really, really, really need to do the escaping yourself (of which there is no sign in your example):

string EncodeMySqlString(string value) {
   return value.Replace(@"\", @"\\").Replace("'", @"\'")
}
Guffa
No, not for SQL.
erikkallen
@erikkallen: No, it's not for MS SQL Server. Please check what the question is about before voting down...
Guffa
OK, sorry. Unfortunately, can't remove downvote.
erikkallen
A: 

If you need to perform database operations, such as creating tables, then you should use SQL Server Management Objects instead of executing SQL strings.

For CRUD operations parameters is absolutely the only true path.

UPDATE: It appears that the MySQL client library contains a helper method for this ill-advised task. You can call MySqlHelper.EscapeString(string).

Jamie Ide
Err..thanks, but I am using MySQL. Any way in that case?
Snake
Sorry, I didn't notice the tag. I don't know of a similar library fro MySQL.
Jamie Ide
Ok, thanks! Also I cannot probably do it better.
Snake
A: 

I think the only thing you need to do is value = value.Replace("'", "''")

Of course you shouldn't do this, but you know that.

Edit: Apparantly this is all wrong for MySQL. It should work for PostgreSQL, MS SQL and Oracle, though.

erikkallen
Notice that this is for MySQL, not MS SQL Server. The method that you suggested is ABSOLUTELY NOT sufficient for escaping strings for MySQL.
Guffa