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

从DGV(C#)更新SQLite数据库,c#,database,sqlite,datagridview,C#,Database,Sqlite,Datagridview,在一张表格上,我有一个dgv。从另一个表单,我可以向dgv添加一个项目,还可以将新项目放入SQLite数据库 我试图做的是也能够从dgv编辑项目,并将编辑保存在数据库中 我有CellEndEdit事件的代码: SetConnection(); sqlconnection.Open(); this.dataGridView1.Rows[e.RowIndex].Selected = true; this

在一张表格上,我有一个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中唯一存在的项)并尝试编辑它(又名change name等)时,我会遇到以下错误:SQL逻辑错误或缺少数据库 接近“”:语法错误

注意:当dgv为空且我添加了新项时,新项将成功添加到数据库表中


还要注意:“id”是主键,并且是自动递增的

这里的情况是,当您向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读取值并将其应用于表的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");
                }
            }
        }
    }
}

您也应该参数化ID。不要将其连接到字符串中。如果您的意思是这样的:
sqlcmd.Parameters.Add(新的SQLiteParameter(“@item”,this.dataGridView1.Rows[this.rowIndex1].Cells[“item1”].Value))我仍然遇到同样的问题…我是说参数化ID。我不是说它肯定会解决您的问题,但它可能会。我不认为这能解决问题:/你应该提供更多的代码来分析问题。主要是用于将数据设置为dgv的代码,以及setConnection()方法等