//简单事务实现代码
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();
}
}
标签:事务,Parameters,C#,代码,cmd,amount,cnn,trans,productID From: https://www.cnblogs.com/KevinSteven/p/17737053.html