13

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#

2 Answers 2

33

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.

3
  • What do i do if i have multiple params? do i write cmd.CommandText = "insert ... @parameter ... @parameter"; cmd.Parameters.Add(...);cmd.Parameters.Add(...); ?
    – user34537
    Mar 11, 2009 at 3:53
  • 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. Mar 11, 2009 at 3:59
  • You can call Parameters.Add multiple times just as you have asked or use the Parameters.AddRange which accepts an array of parameters.
    – bstoney
    Mar 11, 2009 at 4:07
1

You can also replace all single quote delimiters with doubt single quotes (not ").

sql = sql.Replace("'","''");
5
  • 2
    This Method is not recommended, It may lead to strange bugs.
    – Palani
    Mar 11, 2009 at 4:03
  • 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. :)
    – klkitchens
    Mar 11, 2009 at 4:28
  • this method is good if you need to create a SQL safe to dump to a text file or such.
    – Alec Gorge
    Jul 20, 2010 at 18:23
  • Sometimes this method works when you build your queries dynamically.
    – EBAG
    Feb 8, 2011 at 16:09
  • 2
    Only use this method if you seriously want to lose your job. Not kidding here.
    – Aur Saraf
    Feb 16, 2015 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.