SQL escape with sqlite in C#

13,586

Solution 1

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.

Solution 2

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

sql = sql.Replace("'","''");
Share:
13,586

Related videos on Youtube

Admin
Author by

Admin

Updated on March 11, 2020

Comments

  • Admin
    Admin about 4 years

    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#

  • Admin
    Admin about 15 years
    What do i do if i have multiple params? do i write cmd.CommandText = "insert ... @parameter ... @parameter"; cmd.Parameters.Add(...);cmd.Parameters.Add(...); ?
  • Quintin Robinson
    Quintin Robinson about 15 years
    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.
  • Palani
    Palani about 15 years
    This Method is not recommended, It may lead to strange bugs.
  • bstoney
    bstoney about 15 years
    You can call Parameters.Add multiple times just as you have asked or use the Parameters.AddRange which accepts an array of parameters.

Related