从 DGV (C#) 更新 SQLite 数据库

Updating SQLite DB from DGV (C#)

在一种形式上,我有一个 dgv。从另一种形式,我可以向 dgv 添加一个项目,并将新项目放入 SQLite 数据库。

我正在尝试做的也是能够从 dgv 编辑项目,并将编辑也保存在数据库中。

我有 CellEndEdit 事件的代码:

            SetConnection();
            sqlconnection.Open();

            this.dataGridView1.Rows[e.RowIndex].Selected = true;
            this.rowIndex1 = e.RowIndex;
            this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[0]; 

            sqlcmd = new SQLiteCommand("UPDATE table1 SET item = @item, quantity = @quantity WHERE id= " + this.dataGridView1.Rows[this.rowIndex1].Cells["id"].Value, sqlconnection);
            sqlcmd.Parameters.AddWithValue("@item", this.dataGridView1.Rows[this.rowIndex1].Cells["item1"].Value);
            sqlcmd.Parameters.AddWithValue("@quantity", this.dataGridView1.Rows[this.rowIndex1].Cells["quantity1"].Value);

            sqlcmd.ExecuteNonQuery();

            sqlconnection.Close();

此代码有效,但前提是我将数据库加载到 dgv。

程序首次打开时,数据库未加载到 dgv 中。我 运行 遇到的问题是,当我添加一个新项目(并且它是 dgv 中唯一存在的项目)时,我尝试对其进行编辑(也就是更改 name.etc),我得到了以下错误:SQL 逻辑错误或缺少数据库 “ ”附近:语法错误

注意:当dgv为空时,我添加了一个新项,新项成功添加到数据库中table。

另请注意:'id' 是 PRIMARY KEY 和 AUTOINCREMENTed

您在这里遇到的情况是,当您向 DGV 添加新项目时,您没有为 ID 列提供值。所以在查询结束时

"UPDATE table1 SET item = @item, quantity = @quantity WHERE id= " + this.dataGridView1.Rows[this.rowIndex1].Cells["id"].Value

这会变成 id = . 因为 DGV 中的 ID 列当前为空并且肯定是 语法错误

它在您加载数据时起作用,因为您正在填充此列。因此解决方案是在插入新项目时正确地为 ID 列提供值。

向数据库插入条目后,使用查询获取自动递增的 ID

Select last_insert_rowid();

使用reader读取值并将其应用于table

的ID列

这对我有用。

private void btnUpdate_Click(object sender, EventArgs e)
{

    using (SqlConnection con = new SqlConnection("Server=your_server_name;Database=your_db_name;Trusted_Connection=True;"))
    {

        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Courses", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                {
                    SqlCommandBuilder sqlcmd = new SqlCommandBuilder(da);
                    DataSet ds = new System.Data.DataSet(); // remove this line
                    da.Update(this.ds, "Courses");
                }
            }
        }
    }
}