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();
}
//启动一个本地事务
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();
}
相关文章推荐
- 【转载】事务的使用(ADO.NET和SQL SERVER)
- 在ADO.NET中使用事务保护数据的完整性(3)
- 使用ADO.NET 实现事务处理
- ADO.NET中事务的使用
- 在ADO.NET中使用事务保护数据的完整性(5)
- ADO.NET中使用事务进行数据库读写的办法
- 在ADO.NET中使用事务保护数据的完整性(1)
- sqldatareader返回数据集,并要求使用ADO.net事务的解决方案
- ado.net中事务的使用
- 转:事务的使用(ADO.NET和SQL SERVER)
- 在ADO.NET中使用事务保护数据的完整性(3)
- 在ADO.NET中使用事务保护数据的完整性(2)
- 使用ADO.NET配置SQLServer事务处理
- 在ADO.NET中使用事务保护数据的完整性(1)
- 在C#和ado.net中使用事务
- 用ADO.NET来使用事务
- ADO.NET使用事务出错的解决(MSDTC)
- 事务的使用(ADO.NET和SQL SERVER)
- [转载]C#中使用ADO.NET连接SQL Server数据库,自动增长字段用作主键,处理事务时的基本方法
- 在传统的ADO.NET中使用事务