C#执行Sql事务处理

 

None.gif
None.gif
// 执行事务处理
None.gif
public   void  DoTran()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {  //建立连接并打开
InBlock.gif
 SqlConnection myConn=GetConn();
InBlock.gif myConn.Open();
InBlock.gif SqlCommand myComm
=new SqlCommand();
InBlock.gif 
//SqlTransaction myTran=new SqlTransaction();
InBlock.gif 
//注意,SqlTransaction类无公开的构造函数
InBlock.gif
 SqlTransaction myTran;
InBlock.gif 
//创建一个事务
InBlock.gif
 myTran=myConn.BeginTransaction();
InBlock.gif 
try
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
//从此开始,基于该连接的数据操作都被认为是事务的一部分
InBlock.gif  
//下面绑定连接和事务对象
InBlock.gif
  myComm.Connection=myConn;
InBlock.gif  myComm.Transaction
=myTran; //定位到pubs数据库
InBlock.gif
  myComm.CommandText="USE pubs";
InBlock.gif  myComm.ExecuteNonQuery();
//更新数据
InBlock.gif  
//将所有的计算机类图书
InBlock.gif
  myComm.CommandText="UPDATE roysched SET royalty = royalty * 1.10 WHERE title_id LIKE 'Pc%'";
InBlock.gif  myComm.ExecuteNonQuery();
InBlock.gif   
//提交事务
InBlock.gif
  myTran.Commit();
ExpandedSubBlockEnd.gif }

InBlock.gif 
catch(Exception err)
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
throw new ApplicationException("事务操作出错,系统信息:"+err.Message);
ExpandedSubBlockEnd.gif  }

InBlock.gif 
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  myConn.Close();
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif 
private  SqlConnection GetConn()
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif {
InBlock.gif   
string strSql="Data Source=localhost;Integrated Security=SSPI;user id=sa;password=";
InBlock.gif   SqlConnection myConn
=new SqlConnection(strSql);
InBlock.gif   
return myConn;
ExpandedBlockEnd.gif  }

None.gif }
None.gif 
public   class  Test
ExpandedBlockStart.gifContractedBlock.gif 
dot.gif {
InBlock.gif  
public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   DbTranSql tranTest
=new DbTranSql();
InBlock.gif   tranTest.DoTran();
InBlock.gif   Console.WriteLine(
"事务处理已经成功完成。");
InBlock.gif   Console.ReadLine();
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif }
 
posted on 2006-10-15 16:00 吴勇 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/wuyong/archive/2006/10/15/529514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值