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?
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