sql1="INSERT INTO tablename(Id,col1,col2) VALUES(@Id,@col1,@col2) update tablename2 set col=@col"; sql2="INSERT INTO tablename3(Id,col1,col2) VALUES(@Id,@col1,@col2)"; //参数设置(略) using(SqlTransaction tran = SqlHelper.BeginTransaction(SqlHelper.DBConnectionString)) { try { SqlHelper.ExecuteNonQuery(tran,CommandType.Text,sql1,parms); SqlHelper.ExecuteNonQuery(tran,CommandType.Text,sql2,parms); tran.Commit(); return true; } catch { tran.Rollback(); return false; }
放在sqlhelper.cs中
public static SqlTransaction BeginTransaction(string con) { SqlConnection connection = new SqlConnection(con); connection.Open(); SqlTransaction tran = connection.BeginTransaction(); return tran; }