2012-03-04 51 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 +"'");