ADO.NET中实现事务处理
在数据库连接上创建事务处理对象,然后调用事务处理对象来提交事务或回滚事务。
Demo:
Demo:
private void btnOK_Click(object sender, System.EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Server=(local);Initial Catalog=Northwind;uid=sa;pwd=111;");
myConnection.Open();
// 启动一个事务
SqlTransaction myTrans = myConnection.BeginTransaction();
// 为事务创建一个命令
SqlCommand myCommand = new SqlCommand();
myCommand.Connection=myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (110, 'Description')";
myCommand.ExecuteNonQuery();
//myTrans.Commit();
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (111, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Response.Write("成功写入记录!");
}
catch(Exception Ex)
{
myTrans.Rollback();
Response.Write(Ex.ToString());
Response.Write("写入数据库失败!");
}
finally
{
myConnection.Close();
}
}
{
SqlConnection myConnection = new SqlConnection("Server=(local);Initial Catalog=Northwind;uid=sa;pwd=111;");
myConnection.Open();
// 启动一个事务
SqlTransaction myTrans = myConnection.BeginTransaction();
// 为事务创建一个命令
SqlCommand myCommand = new SqlCommand();
myCommand.Connection=myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (110, 'Description')";
myCommand.ExecuteNonQuery();
//myTrans.Commit();
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (111, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Response.Write("成功写入记录!");
}
catch(Exception Ex)
{
myTrans.Rollback();
Response.Write(Ex.ToString());
Response.Write("写入数据库失败!");
}
finally
{
myConnection.Close();
}
}