首页  ·  知识 ·  云计算
ASP.NET和SQLSERVER中使用事务示例
佚名  http://www.cnblogs.com/idotnet8/  综合  编辑:dezai  图片来源:网络
"FONT-SIZE: 10pt"> "FONT-SIZE: 12pt; COLOR: #0000ff">1,SqlServer存储过程的事务处理一种比较通用的出错处理的模式

1,SqlServer存储过程的事务处理
一种比较通用的出错处理的模式大概如下:
Create procdure prInsertProducts
(
 @intProductId int,
 @chvProductName varchar(30),
 @intProductCount int
)
AS
Declare @intErrorCode int
Select @intErrorCode=@@Error
Begin transaction
 if @intErrorCode=0
   begin
     -insert products
     insert products(ProductID,ProductName,ProductCount)
     s(@intProductId,@chvProductName,@intProductCount)
     Select @intErrorCode=@@Error --每执行完一条t-sql语句马上进行检测,并把错误号保存到局部变量中
   end
 if @intErrorCode=0
   begin
     -update products
     update products set ProductName='MicroComputer' where ProductID=5
     Select @intErrorCode=@@Error
   end
if @intErrorCode=0
   commit transaction
else
   rollback transaction

 Return @intErrorCode --最好返回错误代号给调用的存储过程或应用程序

2,.Net中使用事务处理
SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
myConnection.Open();

SqlTransaction myTrans = myConnection***ginTransaction(); //使用New新生成一个事务
SqlCommand myCommand = new SqlCommand();
myCommand.Transaction = myTrans;

try
{
myCommand.CommandText = "Update Address set location='23 rain street' where userid='0001'";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Record is udated.");
}
catch(Exception e)
{
myTrans.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Sorry, Record can not be updated.");
}
finally
{
myConnection.Close();
}


说明:在SqlServer中,每条Sql语句都作为一个事务来执行,所以无论在存储过程,还是在.net代码中使用,执行单条Sql语句没有必要使用事务处理,上面只是为了简化表达而对单条Sql语句使用事务处理

本文作者:佚名 来源:http://www.cnblogs.com/idotnet8/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读