我正在使用C#和MYSQL,并且Rollback无法正常工作。我有三个删除语句,其中表第三个删除SQL不存在,在catch我正在做回滚,但它只发生在第三次
string id = dataGridView1.Rows[index].Cells[0].Value.ToString();
string strDelete = "DELETE FROM user WHERE id = " + id;
OdbcTransaction transaction = null;
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = Singleton.Instance.GetConnection();
transaction = Singleton.Instance.GetConnection().BeginTransaction();
cmd.Transaction = transaction;
try
{
cmd.CommandText = strDelete;
cmd.ExecuteNonQuery();
// delete from userdata
strDelete = "DELETE FROM userdata WHERE id = " + id;
cmd.CommandText = strDelete;
cmd.ExecuteNonQuery();
// delete from usersystem
strDelete = "DELETE FROM usersystem WHERE id = " + id;
cmd.CommandText = strDelete;
cmd.ExecuteNonQuery();
// delete from user systemstatus. here table don't exists, will throw
// exception
strDelete = "DELETE FROM usersystemstatusAAAA WHERE id = " + id;
cmd.CommandText = strDelete;
cmd.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
这里提交前两个SQL语句,同时假设要回滚所有。
答案 0 :(得分:4)
您需要检查MySQL数据库的存储类型。并非所有存储都是事务性的。例如,InnoDB有交易而MyISAM没有交易。
MyISAM与InnoDB MyISAM versus InnoDB
答案 1 :(得分:2)
我怀疑你有第二个连接,并且连接/事务/命令存在混淆;尝试在您实际使用的连接上启动事务:
cmd.Connection = Singleton.Instance.GetConnection();
transaction = cmd.Connection.BeginTransaction();
另外,您可能希望在此处查看using
块。