Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite "Update" C# Syntax Error

Hi following Code gives a Syntax Error.I don't know how to fix the Problem.

The Error

{"SQLite error\r\nnear \"Mytext\": syntax error"}

My Code

string dataSource = "Database.s3db";
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + dataSource;
connection.Open();
SQLiteCommand command = new SQLiteCommand(connection);
command.CommandText = ("update Example set Info ='" + textBox2.Text + ", Text ='"+textBox3.Text + "where ID ='" + textBox1.Text +"'");
command.ExecuteNonQuery();
like image 355
user1248067 Avatar asked Mar 04 '12 15:03

user1248067


1 Answers

Others have suggested alternative ways of constructing the SQL, but you shouldn't be including the values in the SQL at all. You should be using a parameterized query, which avoids SQL injection attacks amongst other things.

It's not immediately clear to me which driver you're using, but assuming it's the Devart.com one, the documentation for SQLiteCommand.Parameters gives a good example of how to do this. In your case, the code would become something like:

string dataSource = "Database.s3db";
using (SQLiteConnection connection = new SQLiteConnection())
{
    connection.ConnectionString = "Data Source=" + dataSource;
    connection.Open();
    using (SQLiteCommand command = new SQLiteCommand(connection))
    {
        command.CommandText =
            "update Example set Info = :info, Text = :text where ID=:id";
        command.Parameters.Add("info", DbType.String).Value = textBox2.Text; 
        command.Parameters.Add("text", DbType.String).Value = textBox3.Text; 
        command.Parameters.Add("id", DbType.String).Value = textBox1.Text; 
        command.ExecuteNonQuery();
    }
}
like image 112
Jon Skeet Avatar answered Oct 22 '22 20:10

Jon Skeet