我在创建mysql表时语句有加ENGINE=InnoDB,然后下面是我的事务
百度说只有存储引擎为ENGINE=InnoDB才可以用事务
public static bool NonQuery(string connStr, string firstSql, string secondSql, out string strErrorInfo)
{
strErrorInfo = "";
bool flag = false;
using (MySqlConnection conn = new MySqlConnection(connStr))
{
if (conn.State != ConnectionState.Open)
conn.Open();
MySqlTransaction transaction = conn.BeginTransaction();
MySqlCommand comm = new MySqlCommand();
comm.Connection = conn;
comm.Transaction = transaction;
try
{
comm.CommandText = firstSql;
if (comm.ExecuteNonQuery() > 0)
{
comm.CommandText = secondSql;
if (comm.ExecuteNonQuery() > 0)
{
flag = true;
}
else
{
flag = false;
}
}
else
{
flag = false;
}
transaction.Commit();
}
catch (Exception ex)
{
strErrorInfo = ex.Message + ex.StackTrace;
transaction.Rollback();
// string sql = "DROP TABLE if EXISTS `tmp_Card`;";
// comm.CommandText = sql;
//comm.ExecuteNonQuery();
}
//finally
//{
// comm.Dispose();
// conn.Close();
//}
return flag;
}
}
http://blog.csdn.net/ying_593254979/article/details/12095169
看了好多说要修改@@autocommit这个;因为默认的为自动提交为1;
但是我应用程序中已经明确了 conn.BeginTransaction();还需要设置这个@@autocommit?
是的,需要设置。
conn.BeginTransaction(); 对应的SQL是 START TRANSACTION
而设置autocommit的SQL是 SET autocommit=1
参考: