views:

68

answers:

1

I am writing some code to store names in a database. I limit the names to only certain characters, but last names are a challenge. Since some people have single quotes in their name (example O'Brian) I need to allow this. So I wrote a regex replace to replace the ' with a \' which I assumed should make the ' a literal. It works as far as replacement goes, but it still marks the end of the string, and I get the error

There was an error parsing the query. [ Token line number=1, token line offeset = 71, token in error=Brian]

I understand the error, the single quote marks the end of the string to be entered leaving the rest of the string Brian outside the quotes.

The code I am using:

Regex reg = new Regex("\'");
firstName = reg.Replace(firstName, "\\'");
lastName = reg.Replace(lastName, "\\'"):

Then the select query is built with string.format

sqlInsertObj.CommandText = string.Format("INSERT INTO childNameId (childFName, childLName) VALUES ('{0}', '{1}')", fName, lName);
 sqlInsertObj.ExecuteNonQuery();

This works for any entry, except when there is a quote in the name.

+2  A: 

It's better to use parameterized sql queries, instead of building them with string concatenation. Documentation and an example can be found at MSDN.

If you insist on string concatenation escape it with a double single quote instead of \.

firstName = firstName.Replace("'", "''" );
Mikael Svenson
I tried that, it still throws an exception.
Dusty Lew
Ok, thanks. I was trying to convert how I have worked with MySQL in the past into sql ce. It is weird though, that the double quote throws an exception still. Thanks, I will look into the parameterized sql queries. Is there any reason that it is better?
Dusty Lew
Parameterized queries are the only way you should do this. They avoid more problems than just single quotes. It's also a security problem if you don't use them, because it'll leave you far more vulnerable to SQL injection attacks
Sander Rijken
@Sander: thanks for explaining what i meant by "better". I was a bit quick writing it.
Mikael Svenson
@Dusty: do you get the same exception? And mysql also supports parameterized queries. I've used that in the past.
Mikael Svenson
Parametized queries protect against sql injections, so does that mean that I don't need the regex I wrote to only allow certain characters before inserting the data into my database? and no, the exception was having to do with there being no column, it was acting like I was trying to insert 3 separate values, but had only defined two columns for them to go into. So, for some reason the double single quote wasn't acting as an escape character, but instead marking the end of the value.
Dusty Lew
@Dusty: Correct, you can skip the regex and send the real value unmodified in the parameter. Easier and safer.
Mikael Svenson
Perfect, this is exactly what I needed. Thank you so much.
Dusty Lew