Sqlite“更新”C#语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9556135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:52:42  来源:igfitidea点击:

Sqlite "Update" C# Syntax Error

c#sqlsqlitesyntax

提问by user1248067

Hi following Code gives a Syntax Error.I don't know how to fix the Problem.

嗨,以下代码给出了语法错误。我不知道如何解决问题。

The Error

错误

{"SQLite error\r\nnear \"Mytext\": syntax error"}

{"SQLite 错误\r\near \"Mytext\": 语法错误"}

My Code

我的代码

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

采纳答案by Jon Skeet

Others have suggested alternative ways of constructing the SQL, but you shouldn't be including the values in the SQL at all. You should be using a parameterized query, which avoids SQL injection attacksamongst other things.

其他人提出了构建 SQL 的替代方法,但您根本不应该在 SQL 中包含这些值。您应该使用参数化查询,这可以避免SQL 注入攻击等。

It's not immediately clear to me which driver you're using, but assuming it's the Devart.com one, the documentation for SQLiteCommand.Parametersgives a good example of how to do this. In your case, the code would become something like:

我不是很清楚您正在使用哪个驱动程序,但假设它是 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();
    }
}