如何在 C# 中使用 using 语句进行错误处理
我正在尝试从多个数据库表中删除记录。对于错误处理,我使用 try/catch 块,如下所示。
try
{
using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
{
oConn.Open();
using (SqlCeTransaction transaction = oConn.BeginTransaction())
{
//delete from multiple tables using ADO.NET
transaction.Commit();
}
}
}
catch
{
//error handling
}
问题是当引发异常时事务不会回滚。在阅读多个论坛时,我的结论是“使用”语句应该处理事务和连接。处置时,应回滚未提交的事务。
有人可以告诉我我做错了什么吗?
im trying to do delete records from multiple database tables. For error handling i'm using a try/catch block as seen beneath.
try
{
using (SqlCeConnection oConn = new SqlCeConnection(ConnectionString))
{
oConn.Open();
using (SqlCeTransaction transaction = oConn.BeginTransaction())
{
//delete from multiple tables using ADO.NET
transaction.Commit();
}
}
}
catch
{
//error handling
}
problem is when an exception is raised the transaction is not rolled back. When reading multiple forums my conclusion is that 'using' statements should dispose the transaction and the connection. When disposed, the uncommitted transaction should be rolled back.
Can someone tell me what I'm doing wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的猜测是您没有设置
SqlCeCommand
的Transaction
属性(您没有显示)。SqlCeCommand
不会自动加入事务,您必须显式设置它。据我所知,Transaction
的Dispose()
应该将其回滚,但您可以自己调用Rollback()
作为其他人建议只是为了确定。My guess is that you're not setting the
Transaction
property of yourSqlCeCommand
(which you don't show).The
SqlCeCommand
won't automatically enlist in the transaction, you have to set it explicitly. As far as I'm aware, theDispose()
of theTransaction
should roll it back, but you can callRollback()
yourself as others suggest just to be sure.为了安全起见:
我找不到直接说明事务默认回滚的文档。
To play it safe:
I couldn't find a direct piece of documentation that states a transaction is rolled back by default.
基本上,您的
try{...} catch{}
块位于错误的位置。它应该在 using 语句中,最好在transaction.Commit
周围Basically your
try{...} catch{}
block is in the wrong place. It should be within the using statement, preferably around thetransaction.Commit