在带有事务“并发冲突”的 Ado.Net 更新中
Posted
技术标签:
【中文标题】在带有事务“并发冲突”的 Ado.Net 更新中【英文标题】:In Ado.Net Update winth transaction "Concurrency violation" 【发布时间】:2011-12-02 17:09:30 【问题描述】:我在 mysql 5.5、C#、ADO.NET、DataSet 上编写。 我有一个 DataSet 和 DataAdapter 填充它。在 DataAdapter 中,我覆盖了 INSERT、UPDATE、DELETE 命令。当我使用存储过程时,就像这些命令一样,一切都很好。 但是,当我在这个存储过程中使用事务时,我得到一个异常:
并发冲突:DeleteCommand 影响了预期的 1 条记录中的 0 条。
我可以用这个错误做什么?
示例:http://dl.dropbox.com/u/46828938/DataGridSample.zip
重现问题:从 Datagrid 中删除行并按“更新”按钮。
DBConcurrencyException(“并发冲突:DeleteCommand 影响了预期的 1 条记录中的 0 条。”)重现于:“productDataAdapter.Update(dataSet, "Products");"字符串。
【问题讨论】:
【参考方案1】:我学习了很多关于这个问题的文档(msdn、mysql 论坛、*** 等)并查看:
检查真正的并发性或是否可能做额外的查询:
insert
:获取最后插入的行并与插入的行进行比较。
update
:获取更新的行(例如按键)并与更新的行进行比较。
delete
:尝试获取行(例如通过键)并获取 null。
当然,上述所有比较都必须在一个逻辑浴/连接等中进行。 不幸的是,不存在其他检查“并发冲突”或不在 MySql 上的方法。(与其他数据库服务器不同)。
我希望这些信息对某人有所帮助。
【讨论】:
【参考方案2】:SqlCommand com = new SqlCommand("insert into student_info values(@id,@name,@batch)",con);
com.Parameters.Add(new SqlParameter("@id", dataGridView1.CurrentRow.Cells[0].Value));
com.Parameters.Add(new SqlParameter("@name", dataGridView1.CurrentRow.Cells[1].Value) );
com.Parameters.Add(new SqlParameter("@batch", dataGridView1.CurrentRow.Cells[2].Value));
da.InsertCommand = com;
com = new SqlCommand("update student_info set name = @name, batch = @batch where s_id = @id", con);
com.Parameters.Add(new SqlParameter("@id", dataGridView1.CurrentRow.Cells[0].Value));
com.Parameters.Add(new SqlParameter("@name", dataGridView1.CurrentRow.Cells[1].Value));
com.Parameters.Add(new SqlParameter("@batch", dataGridView1.CurrentRow.Cells[2].Value));
da.UpdateCommand = com;
com = new SqlCommand("delete from student_info where s_id = @id", con);
com.Parameters.Add(new SqlParameter("@id", dataGridView1.Rows[(dataGridView1.CurrentRow.Index -1)].Cells[0].Value));
您是否使用上述方法?幸运的是,我已经找到了这个异常的原因,但仍在寻找答案。 出现错误是因为我们正在使用 dataGridView 的 CurrentRow 属性。它适用于插入和更新命令。但是当我们为删除命令选择 cuurentRow 时,datagridview 实际上会选择下一行。如果存在下一条记录,则将其删除,否则将引发这样的错误。我仍在寻找答案。等到您可以使用 CommandBuilder 时,它就可以正常工作了。
【讨论】:
以上是关于在带有事务“并发冲突”的 Ado.Net 更新中的主要内容,如果未能解决你的问题,请参考以下文章
Entity Framework Core 数据保存原理详解