c# 下访问mysql使用事务处理的问题
publicstaticboolExecuteTransaction(stringconnectionString,CommandTypecmdType,List<str...
public static bool ExecuteTransaction(string connectionString, CommandType cmdType, List<string> cmdTexts)
{
MySqlConnection myConnection = new MySqlConnection(connectionString); //get the connection object
myConnection.Open(); //open the connection
MySqlTransaction myTrans = (MySqlTransaction)myConnection.BeginTransaction(); //begin a trascation
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = myConnection;
cmd.CommandType = CommandType.Text;
cmd.Transaction = myTrans;
try
{
foreach (string i in cmdTexts)
{
cmd.CommandText = i;
cmd.ExecuteNonQuery();
}
myTrans.Commit();
}
catch
{
myTrans.Rollback();
return false;
}
finally
{
myConnection.Close();
}
return true;
}
使用这个方法执行mysql的语句,虽然遇到问题,可以执行rollback,但是之前插入的数据,依然已经写入。
调用方式为:
List<string> list = new List<string>();
string sql = "insert into test(name)values(1)";
list.Add(sql);
sql = "insert into test(name)values(aa)";
list.Add(sql);
mysqlDB.MySqlHelper.ExecuteTransaction(conn, System.Data.CommandType.Text, list); 展开
{
MySqlConnection myConnection = new MySqlConnection(connectionString); //get the connection object
myConnection.Open(); //open the connection
MySqlTransaction myTrans = (MySqlTransaction)myConnection.BeginTransaction(); //begin a trascation
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = myConnection;
cmd.CommandType = CommandType.Text;
cmd.Transaction = myTrans;
try
{
foreach (string i in cmdTexts)
{
cmd.CommandText = i;
cmd.ExecuteNonQuery();
}
myTrans.Commit();
}
catch
{
myTrans.Rollback();
return false;
}
finally
{
myConnection.Close();
}
return true;
}
使用这个方法执行mysql的语句,虽然遇到问题,可以执行rollback,但是之前插入的数据,依然已经写入。
调用方式为:
List<string> list = new List<string>();
string sql = "insert into test(name)values(1)";
list.Add(sql);
sql = "insert into test(name)values(aa)";
list.Add(sql);
mysqlDB.MySqlHelper.ExecuteTransaction(conn, System.Data.CommandType.Text, list); 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询