回滚在C#中不起作用
本文关键字:不起作用 | 更新日期: 2023-09-27 18:21:39
我正在使用C#和MYSQL,回滚不起作用。我有三个delete语句,其中表第三个delete 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语句被提交,同时假定回滚所有语句。
您需要检查MySQL数据库的存储类型。并非所有存储都是事务性的。例如,InnoDB有事务,而MyISAM没有。
MyISAM与InnoDBMyISAM与InnoDB
我怀疑您有第二个连接,并且对连接/事务/命令存在混淆;尝试在您实际使用的连接上启动事务:
cmd.Connection = Singleton.Instance.GetConnection();
transaction = cmd.Connection.BeginTransaction();
此外,您可能希望在此处查看using
块。