C# 事务实现代码

 //简单事务实现代码

static void Test()

{
DataTable dt = new DataTable();
SqlConnection cnn = new SqlConnection("连接字符串");
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cnn.Open();
SqlTransaction trans = cnn.BeginTransaction(); //开启事务
try
{
foreach (DataRow dr in dt.Rows)
{
cmd.CommandText = "update Product set amount = @amount where productID = @productID";
cmd.Parameters.Add("@amount", SqlDbType.Int);
cmd.Parameters["@amount"].Value = Convert.ToInt32(dr["amount"]);
cmd.Parameters.Add("@productID", SqlDbType.VarChar);
cmd.Parameters["@productID"].Value = dr["productID"].ToString();
cmd.ExecuteNonQuery();
}
trans.Commit(); //成功提交
}
catch (Exception)
{
trans.Rollback(); //出错事务回滚
}
finally
{
cnn.Close();
trans.Dispose();
cnn.Dispose();
}
}

 

posted @ 2023-09-29 15:59  KevinSteven  阅读(29)  评论(0编辑  收藏  举报