您好以下代码提供语法错误。我不知道如何解决问题。
错误
{“SQLite error \ 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();
答案 0 :(得分:23)
其他人已经提出了构建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();
}
}
答案 1 :(得分:0)
因此,将以上答案用作参数化SQL是最佳实践。
但是,要回答有关语法的问题-有两个问题:
optionalSemicolon :: Parser Bool
optionalSemicolon = fromMaybe False <$> optional (True <$ symbol ";")
在这里,编写完
command.CommandText = ("update Example set Info ='" + textBox2.Text + ", Text ='"+textBox3.Text + "where ID ='" + textBox1.Text +"'");
应为:
set Info ='" + textBox2.Text + ", Text
^^,双引号后加一个'。
您在textBox3上犯了同样的错误。
此外,set Info ='" + textBox2.Text + "', Text
where关键字前没有空格。
提示:遇到此类错误时,将SQL输出到控制台并检查构造的字符串。但是参数化是最好的方法。