I am using C# and MYSQL and the Rollback is not working. I have three delete statement where the table third delete SQL don’t exists and in catch i am doing rollback but its only happening for third while
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);
}
}
Here the first two SQL statements are committed while suppose to rollback all.
You need to check the storage type of your MySQL database. Not all storages are transactional. For example InnoDB has transactions while MyISAM does not.
MyISAM versus InnoDB
MyISAM versus InnoDB