从DGV更新SQLite DB(C#)

问题描述 投票:0回答:2

在一个表格上我有一个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中唯一的项目)时,我尝试编辑它(又名。更改名称.etc。),我收到以下错误:SQL逻辑错误或者在“”附近缺少数据库:语法错误

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

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

c# database sqlite datagridview
2个回答
0
投票

您在这里遇到的情况是,当您向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列


0
投票

这适合我。

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");
                }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.