tags:

views:

101

answers:

3

I'm trying to do datacontent.executeCommand("string") in C#. When I am trying to do Insertion I am having trouble because everytime there is a 'word' in a entry I thinks it's a new column, and i throws an exception.

How do you turn the 'word' into ''word''?

+1  A: 

You can escape characters in SQL strings with \. However, I believe the best solution to your problem (and a bunch of others, that you'll run into later if you don't do it this way from the start) is SQL Parameters.

Tomas Lycken
A: 

I would like to welcome you to the wonderful world of SQL injection, where users can hijack your database by executing malicious SQL due to you executing arbitrary strings ;-)

You really should use parameters (Like those in System.Data.SqlClient) or use the LINQ data model objects generated for you and set values on those and then submit your changes. Let the data access layer escape out your values and protect you from a user that might enter text that includes SQL statements like DELETE * FROM IMPORT_TABLE.

Jason Jackson
+1  A: 

As suggested by Tomas and Jason, it is best to use SQLParameters to avoid these problems.

However, if it requires to many code changes and you need a quick fix, then I would say: You don't need regex for this. You only need to do a string.replace

string query;
...
query.Replace("'", "''");

If I haven't understood your Q properly and its only instances of 'word' you need to change, you can do:

query.Replace("'word'", "''word''");
Rashmi Pandit
Agreed. I have been doing this for years, and provided that you use it everywhere that you yourself are injecting strings into your SQL statements, it is perfectly safe and adequate for the problem at hand.
harpo