【问题标题】:Sqlite "Update" C# Syntax ErrorSqlite“更新”C#语法错误
【发布时间】:2012-03-22 07:18:16
【问题描述】:

您好,以下代码出现语法错误。我不知道如何解决问题。

错误

{"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();

【问题讨论】:

  • 为避免此类错误(和 SQL 注入),您应该使用查询参数,而不是动态创建 SQL 命令字符串。
  • @user1248067:不要按原样使用已接受的答案。您应该真的,真的使用参数化 SQL。

标签: c# sql sqlite syntax


【解决方案1】:

其他人提出了构建 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();
    }
}

【讨论】:

  • 我不确定是否是版本问题;但我不得不使用“DbType.String”代替“SqLiteType.Text”。我正在使用 SQLite 版本 1.0.99
【解决方案2】:

因此,使用上述答案作为参数化 SQL 是最佳实践。

但是,要回答您关于语法的问题 - 有两个问题:

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

在这里,你没有在写完单引号后关闭单引号 set Info ='" + textBox2.Text + ", Text

应该是: set Info ='" + textBox2.Text + "', Text

^^ 在双引号后加上一个 '。

你在 textBox3 上犯了同样的错误。

另外,Text ='"+textBox3.Text + "where

where 关键字前没有空格。

提示:当出现此类错误时,将 SQL 输出到控制台并检查构造的字符串。但参数化是最好的方法。

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多