您的位置:首页 > 其它

ADO.NET事务的使用

2008-03-24 20:01 357 查看
SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
//启动一个本地事务
SqlTransaction myTrans = myConnection.BeginTransaction();
//在当前的事务中登记命令
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText="Insert into Region(RegionID,RegionDescription) Values(100,'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText="Insert into Region(RegionID,RegionDescription) Values(101,'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
System.Console.WriteLine("Both records are written to database");

}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch(SqlException ex)
{
if(myTrans.Connection!=null)
{
Console.WriteLine("An exception " + ex.GetType() + " Was encountered while attempting to roll back the transction.");
}
}
}
finally
{
myConnection.Close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: