2012-03-04 48 views
5

以下代碼給出了一個語法錯誤。我不知道如何解決這個問題。Sqlite「更新」C#語法錯誤

的錯誤

{ 「SQLite的錯誤\ r \ nnear \」 MYTEXT \ 「:語法錯誤」}

我的代碼

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(); 
+2

爲了避免這種錯誤(和SQL注入)的,你應該使用的查詢參數,而不是動態創建的SQL命令字符串。 – svick 2012-03-04 15:37:45

+2

@ user1248067:*請*不要按照原樣使用接受的答案。你應該*真的,真的*使用參數化的SQL。 – 2012-03-04 15:47:52

回答

21

其他人提出了構建SQL的替代方法,但是您不應該在SQL中包含這些值。您應該使用參數化查詢,這可以避免SQL injection attacks等等。

目前尚不清楚您使用的是哪個驅動程序,但假設它是Devart.com之一,SQLiteCommand.Parameters的文檔提供了一個很好的示例。在你的情況下,代碼會變成這樣:

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(); 
    } 
} 
+0

我不確定它是否是版本問題;但我不得不使用「DbType.String」來代替「SqLiteType.Text」。我正在使用SQLite版本1.0.99 – sapbucket 2017-04-06 15:08:15

+0

@sapbucket:嗯......將編輯。 – 2017-04-06 15:11:15

5

你錯過了' 2次

試試這個:

command.CommandText = ("update Example set Info ='" + textBox2.Text + "', Text ='"+textBox3.Text + "' where ID ='" + textBox1.Text +"'");