-
C#执行Sql事务处理
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
//执行事务处理
public void DoTran()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{ //建立连接并打开
SqlConnection myConn=GetConn();
myConn.Open();
SqlCommand myComm=new SqlCommand();
//SqlTransaction myTran=new SqlTransaction();
//注意,SqlTransaction类无公开的构造函数
SqlTransaction myTran;
//创建一个事务
myTran=myConn.BeginTransaction();
try
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
//从此开始,基于该连接的数据操作都被认为是事务的一部分
//下面绑定连接和事务对象
myComm.Connection=myConn;
myComm.Transaction=myTran; //定位到pubs数据库
myComm.CommandText="USE pubs";
myComm.ExecuteNonQuery();//更新数据
//将所有的计算机类图书
myComm.CommandText="UPDATE roysched SET royalty = royalty * 1.10 WHERE title_id LIKE 'Pc%'";
myComm.ExecuteNonQuery();
//提交事务
myTran.Commit();
}
catch(Exception err)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
throw new ApplicationException("事务操作出错,系统信息:"+err.Message);
}
finally
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
myConn.Close();
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
private SqlConnection GetConn()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
string strSql="Data Source=localhost;Integrated Security=SSPI;user id=sa;password=";
SqlConnection myConn=new SqlConnection(strSql);
return myConn;
}
}
public class Test
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public static void Main()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
DbTranSql tranTest=new DbTranSql();
tranTest.DoTran();
Console.WriteLine("事务处理已经成功完成。");
Console.ReadLine();
}
}
-
相关阅读:
Fatal error: Maximum execution time of 30 seconds exceeded in
常见变量命名规则
Rust使用国内镜像安装依赖
flutter使用国内镜像源
7个每天晚上应该坚持的好习惯
网络数据传输格式的思考
Deepin安装 ruby 包管理工具 RVM(适用于 Debian 系列)
C语言数据类型关键字
win10 powershell禁止运行脚本解决
Linux 查看系统相关信息(系统发型版本及内核版本等)
-
原文地址:https://www.cnblogs.com/wuyong/p/529514.html
Copyright © 2020-2023
润新知