当前位置: 移动技术网 > IT编程>开发语言>.net > .Net和SqlServer的事务处理实例

.Net和SqlServer的事务处理实例

2018年11月03日  | 移动技术网IT编程  | 我要评论

广州医学院录取分数线,运城贴金麻将,客车查询时刻表

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) 

     values(@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.begintransaction(); //使用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(); 

}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网