I am working on a c# application with Mysql database(version 5.5).
I am facing an issue where I need to catch an exception occurred in Mysql.
It doesn't matter whether it is caught in Mysql or in dotNet. The problem is that I want to rollback all my previous work when an exception/error is occurred; be it of MySqlException or custom one.
And yes, I tried using TransactionScope
and MySqlTransaction
but it didn't rollback my work.
If anyone has any ideas or suggestions, please guide me.
Thanks.
Edit:Code
MySqlConnection con = new MySqlConnection(cnstring);
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
MySqlCommand cmd;
TransactionScope ob = new TransactionScope();
try
{
cmd = new MySqlCommand("testProcedureSignal", con);
cmd.Parameters.Add(new MySqlParameter("pval", 1));
cmd.Parameters.Add(new MySqlParameter("@intException", MySqlDbType.Int32) { Direction = ParameterDirection.Output });
cmd.Parameters.Add(new MySqlParameter("@strErrorMessage", MySqlDbType.VarChar) { Direction = ParameterDirection.Output });
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
catch (MySqlException e)
{
con.Close();
ob.Dispose();
return;
}
ob.Complete();
con.Close();
And this is the Procdeure:
CREATE PROCEDURE `testProcedureSignal`(
pval INT,
OUT intException INT,
OUT strErrorMessage VARCHAR(255)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN
ROLLBACK;
END;
SET intException = 100;
START TRANSACTION;
INSERT INTO demo (data) values (intException);
SET intException = intException + 10;
INSERT INTO demo (data) values (intException);
DROP TABLE teeeee;-- this table does not exist
INSERT INTO demo2 (data1,data2) values ('demo2',intException + 10);
SET intException = 111;
SET intException = 2;
COMMIT;
END