ado.net 中事务的使用
2024-09-13 22:06:23
SqlHelper 类方法中启用事务
public static int UpdateByTran(List<string> sqlList)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.Transaction = conn.BeginTransaction();//开启事务
int result = ;
foreach (string sql in sqlList)
{
cmd.CommandText = sql;
result += cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit();//提交事务
return result;
}
catch (Exception ex)
{
//写入日志...
if (cmd.Transaction != null)
cmd.Transaction.Rollback();//回滚事务
throw new Exception("调用事务更新方法时出现异常:" + ex.Message);
}
finally
{
if (cmd.Transaction != null)
cmd.Transaction = null;//清除事务
conn.Close();
}
}
调用
static void Main(string[] args)
{
List<string> sqlList = new List<string>()
{
"delete from ScoreList where StudentId=100013",
"delete from ScoreList where StudentId=100014",
"delete from ScoreList where StudentId=100011", "delete from Students where StudentId=100010",
"delete from Students where StudentId=100013",
"delete from Students where StudentId=100014",
"delete from Students where StudentId=100011",
};
string sql = "select count(*) from Students";
Console.WriteLine("删除前学生总数:{0}", SQLHelper.GetSingleResult(sql).ToString());
Console.WriteLine("------------------------------------------------------------");
int result = ;
try
{
result = SQLHelper.UpdateByTran(sqlList);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("------------------------------------------------------------");
}
if (result > )
Console.WriteLine("删除成功!");
else
Console.WriteLine("删除失败!");
Console.WriteLine("------------------------------------------------------------");
Console.WriteLine("删除后学生总数:{0}", SQLHelper.GetSingleResult(sql).ToString());
Console.ReadLine();
}
最新文章
- vi/vim实用命令
- Infinite Scroll–无限分页
- Unity3D基础学习 利用NGUI的Texture播放视频
- CentOS7 部署 tomcat
- android国际化
- Codeforces Round #378 (Div. 2)-C. Epidemic in Monstropolis
- Linux redhat ICE环境安装
- C#使用Selenium+PhantomJS抓取数据
- [Swift]LeetCode76. 最小覆盖子串 | Minimum Window Substring
- 外贸建站之图片预加载JS代码分享
- 基于观察者模式-----otto源码分析
- 【SoftwareTesting】Homework3
- 递归打印lua中的table
- E2E测试框架
- nodejs+mysql入门实例(增)
- 将多行按分隔符";|";合成一行
- scikit-FEM-例1-求解Possion边值问题
- 【Rewrite重定向】Nginx使用rewrite重新定向
- [C语言]类型限定词const解析
- Maven问题合集
热门文章
- JQuery左右切换实现
- ios Programming:The Big Nerd Ranch Guid(6th Edition) (Joe Conway &; AARON HILLEGASS 著)
- Spring 框架的历史
- create-react-app 搭建的项目中,让 antd 通过侧边栏导航 Menu 的 Menu.Item 控制 Content 部分的变化
- 阿里云 qW3xT.4 挖矿病毒问题
- ESP8266 ESP-01调试方法
- 阅读DMA Controller Core 官方手册
- Hyperledger fabric 1.3版本的安装部署(原创多机多Orderer部署
- python 多线程 并发socket实例
- linux 创建软链接