c# - SQLite 简单插入查询

标签 c# .net sqlite

我正在尝试使用 SQLite 作为我的存储。我还使用 nuget 和 using 语句添加了引用 dll。

我有

private void SetConnection()
{
            sql_con = new SQLiteConnection
                ("Data Source=c:\\Dev\\MYApp.sqlite;Version=3;New=False;Compress=True;");
}

private void ExecuteQuery(string txtQuery)
{
            SetConnection();
            sql_con.Open();
            sql_cmd = sql_con.CreateCommand();
            sql_cmd.CommandText = txtQuery;
            sql_cmd.ExecuteNonQuery();
            sql_con.Close(); 
}

我正在像这样发送查询文本

public void Create(Book book)
{
            string txtSqlQuery  = "INSERT INTO Book (Id, Title, Language, PublicationDate, Publisher, Edition, OfficialUrl, Description, EBookFormat) ";
            txtSqlQuery += string.Format("VALUES (@{0},@{1},@{2},@{3},@{4},@{5},@{6},@{7},{8})", 
                        book.Id, book.Title, book.Language, book.PublicationDate, book.Publisher, book.Edition, book.OfficialUrl, book.Description, book.EBookFormat);
                   try
                   {
                       ExecuteQuery(txtSqlQuery);
                   }
                   catch (Exception ex )
                   {
                       throw new Exception(ex.Message);
                   }    
}

我的数据库已正确创建并传递了具有有效数据的图书实例。但是在这行代码上执行查询时总是抛出异常:

sql_cmd.ExecuteNonQuery();

我显然在这里做错了什么但我看不到。

更新:抛出的异常信息是

SQL logic error or missing database

unrecognized token: "22cf"

其中 22cf 是传递的 book.Id guid 字符串的一部分。

最佳答案

Don't EVER insert your data in your statement!

使用预处理语句和绑定(bind)参数:

public void Create(Book book) {
    SQLiteCommand insertSQL = new SQLiteCommand("INSERT INTO Book (Id, Title, Language, PublicationDate, Publisher, Edition, OfficialUrl, Description, EBookFormat) VALUES (?,?,?,?,?,?,?,?,?)", sql_con);
    insertSQL.Parameters.Add(book.Id);
    insertSQL.Parameters.Add(book.Title);
    insertSQL.Parameters.Add(book.Language);
    insertSQL.Parameters.Add(book.PublicationDate);
    insertSQL.Parameters.Add(book.Publisher);
    insertSQL.Parameters.Add(book.Edition);
    insertSQL.Parameters.Add(book.OfficialUrl);
    insertSQL.Parameters.Add(book.Description);
    insertSQL.Parameters.Add(book.EBookFormat);
    try {
        insertSQL.ExecuteNonQuery();
    }
    catch (Exception ex) {
        throw new Exception(ex.Message);
    }    
}

关于c# - SQLite 简单插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479166/

相关文章:

c# - 创建唯一图像(GUID 到图像)

c# - 父窗口拦截加速器

c# - 将列表分配给通用列表

c# - 通过参数传递 "IS NULL"

c++ - 在调用 sqlite3_step() 之前我没有记录计数,如何在二维字符串数组中填充记录?

c# - 从字典中获取最大值的键

c# - Automapper 继承的源和目标

asp.net - 图像作为 Asp.Net 5 类库中的资源

sql - SQLite 是否足够强大以用作 wordpress 数据库?

c# - 使用偏移在 Canvas 上绘制点?