I have a text field and its breaking my sql statement. How do i escape all the chars in that field? I am using sqlite with http://sqlite.phxsoftware.com/ in C#
+8
A:
You should be using a parameter as in:
SQLiteCommand cmd = _connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM MyTable WHERE MyColumn = @parameter";
cmd.Parameters.Add( new SQLiteParameter( "@parameter", textfield ) );
SQLiteDataReader reader = cmd.ExecuteReader();
Using a parametrised SQL will escape all input values and help protect you from SQL injection attacks.
bstoney
2009-03-11 03:43:44
What do i do if i have multiple params? do i write cmd.CommandText = "insert ... @parameter ... @parameter"; cmd.Parameters.Add(...);cmd.Parameters.Add(...); ?
acidzombie24
2009-03-11 03:53:57
Yes, there should also be an AddRange method available where you can pass an array of params that match the params in the sql statemenet.
Quintin Robinson
2009-03-11 03:59:31
You can call Parameters.Add multiple times just as you have asked or use the Parameters.AddRange which accepts an array of parameters.
bstoney
2009-03-11 04:07:11
great, thanks! :D
acidzombie24
2009-03-11 04:10:33
A:
You can also replace all single quote delimiters with doubt single quotes (not ").
sql = sql.Replace("'","''");
peiklk
2009-03-11 03:54:42
Not necessarily. If you build your SQL and make the Replace the last step, all should be good. Worked for years without problems. I use the Application Blocks now, so it doesn't matter. :)
peiklk
2009-03-11 04:28:43
this method is good if you need to create a SQL safe to dump to a text file or such.
Ramblingwood
2010-07-20 18:23:46