Sqlite“;更新;C#语法错误
下面的代码给出了一个语法错误。我不知道如何解决这个问题 错误 {“SQLite错误\r\nEAR\“Mytext\”:语法错误“} 我的代码Sqlite“;更新;C#语法错误,c#,sql,sqlite,syntax,C#,Sql,Sqlite,Syntax,下面的代码给出了一个语法错误。我不知道如何解决这个问题 错误 {“SQLite错误\r\nEAR\“Mytext\”:语法错误“} 我的代码 string dataSource = "Database.s3db"; SQLiteConnection connection = new SQLiteConnection(); connection.ConnectionString = "Data Source=" + dataSource; connection.Open(); SQLiteComm
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();
其他人提出了构建SQL的替代方法,但您根本不应该在SQL中包含这些值。您应该使用参数化查询,这样可以避免其他问题 我现在还不清楚您使用的是哪种驱动程序,但假设它是Devart.com驱动程序,则的文档提供了一个很好的示例,说明了如何执行此操作。在您的情况下,代码将类似于:
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();
}
}
因此,使用上述答案作为参数化SQL是最佳实践 但是,要回答您关于语法的问题,有两个问题:
command.CommandText=(“更新示例集信息=””+textBox2.Text+”,Text=“+textBox3.Text+”,其中ID=“+textBox1.Text+”)代码>
在这里,在您编写了
set Info='“+textBox2.Text+”,Text
应该是:
set Info='“+textBox2.Text+”,Text
^^在双引号后加上“结束语”
你在文本框3上犯了同样的错误
另外,Text='“+textBox3.Text+”其中
where关键字前面没有空格
提示:当出现这样的错误时,将SQL输出到控制台并检查构造的字符串。但是参数化是最好的方法。为了避免此类错误(和SQL注入),您应该使用查询参数,而不是动态创建SQL命令字符串。@user1248067:请不要按原样使用接受的答案。你应该真的,真的使用参数化SQL。我不确定这是否是版本问题;但是我不得不用“DbType.String”代替“SqLiteType.Text”。我使用的是SQLite版本1.0.99