使用MySqlTransaction进行回滚
我有一个使用 MySql 5.1.53 和 MySql Connector/Net 6.4.4 的 Visual Studio 2008 C# .NET 3.5 项目。
'protocol_version', '10'
'version', '5.1.53-community-log'
'version_comment', 'MySQL Community Server (GPL)'
'version_compile_machine', 'unknown'
'version_compile_os', 'Win64'
我在数据库中创建一个这样的表。
using (MySqlConnection c = new MySqlConnection(connection_string))
{
c.Open();
using (MySqlCommand cmd = c.CreateCommand())
using (MySqlTransaction xt = c.BeginTransaction())
{
cmd.Connection = c;
cmd.Transaction = xt;
try
{
cmd.CommandText =
@"CREATE TABLE `my_table` (
...
) ENGINE=InnoDB AUTO_INCREMENT=72 DEFAULT CHARSET=latin1";
cmd.ExecuteNonQuery();
throw new System.Exception("This is a simulated failure!!!");
xt.Commit();
}
catch
{
xt.Rollback();
throw;
}
}
}
但是,在模拟失败之后,该表仍然存在于我的数据库中。
我需要做什么才能使事务正确回滚?
I have a Visual Studio 2008 C# .NET 3.5 project using MySql 5.1.53 and MySql Connector/Net 6.4.4.
'protocol_version', '10'
'version', '5.1.53-community-log'
'version_comment', 'MySQL Community Server (GPL)'
'version_compile_machine', 'unknown'
'version_compile_os', 'Win64'
I create a table in my database like this.
using (MySqlConnection c = new MySqlConnection(connection_string))
{
c.Open();
using (MySqlCommand cmd = c.CreateCommand())
using (MySqlTransaction xt = c.BeginTransaction())
{
cmd.Connection = c;
cmd.Transaction = xt;
try
{
cmd.CommandText =
@"CREATE TABLE `my_table` (
...
) ENGINE=InnoDB AUTO_INCREMENT=72 DEFAULT CHARSET=latin1";
cmd.ExecuteNonQuery();
throw new System.Exception("This is a simulated failure!!!");
xt.Commit();
}
catch
{
xt.Rollback();
throw;
}
}
}
But, after the simulated failure the table still exists in my database.
What Do I need to do to make the transaction roll back correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Create Table 语句会导致自动提交。它不参与交易。
请参阅导致隐式提交的语句
在您的情况下,如果发生异常,您可以删除该表。从技术上讲,它不是回滚,但它应该可以满足您的目的。
顺便说一句,你不需要 try catch 块。如果在未调用 Commit 的情况下调用 dispose,事务会自动回滚
Create Table statement causes automatic commit. It doesn't participate in transaction.
See Statements That Cause an Implicit Commit
In your case you can just drop the table if an exception occurs. Its not technically a rollback but it should serve your purpose.
Btw you don't need a try catch block. Transaction is rolled back automatically if dispose is called on it without calling Commit