c#中事务及回滚

时间:2022-08-01 21:11:32

程序一般在特殊数据的时候,会有数据上的同步,这个时候就用到了事物。闲话不多说,直接上代码。

 public void UpdateContactTableByDataSet(DataSet ds, string strTblName)
{
try
{
SqlDataAdapter myAdapter = new SqlDataAdapter();
SqlConnection conn = new SqlConnection("connection string");
SqlCommand myCommand = new SqlCommand("select * from strTblName", conn);
myAdapter.SelectCommand = myCommand;
SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter); conn.Open();
SqlTransaction myTrans = conn.BeginTransaction();
myCommand.Transaction = myTrans; try
{
myAdapter.Update(ds, strTblName);
myTrans.Commit();
}
catch (Exception e)
{
try
{
myTrans.Rollback();//回滚并取消数据库的更新
}
catch (SqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("回滚失败! 异常类型: " + ex.GetType());
}
}
}
finally
{
conn.Close();
} }
catch (Exception ex)
{
throw ex;
}
}

事务回滚主要用于提交失败。(lock)用于处理并发事件。