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();
}

最新文章

  1. vi/vim实用命令
  2. Infinite Scroll–无限分页
  3. Unity3D基础学习 利用NGUI的Texture播放视频
  4. CentOS7 部署 tomcat
  5. android国际化
  6. Codeforces Round #378 (Div. 2)-C. Epidemic in Monstropolis
  7. Linux redhat ICE环境安装
  8. C#使用Selenium+PhantomJS抓取数据
  9. [Swift]LeetCode76. 最小覆盖子串 | Minimum Window Substring
  10. 外贸建站之图片预加载JS代码分享
  11. 基于观察者模式-----otto源码分析
  12. 【SoftwareTesting】Homework3
  13. 递归打印lua中的table
  14. E2E测试框架
  15. nodejs+mysql入门实例(增)
  16. 将多行按分隔符&quot;|&quot;合成一行
  17. scikit-FEM-例1-求解Possion边值问题
  18. 【Rewrite重定向】Nginx使用rewrite重新定向
  19. [C语言]类型限定词const解析
  20. Maven问题合集

热门文章

  1. JQuery左右切换实现
  2. ios Programming:The Big Nerd Ranch Guid(6th Edition) (Joe Conway &amp; AARON HILLEGASS 著)
  3. Spring 框架的历史
  4. create-react-app 搭建的项目中,让 antd 通过侧边栏导航 Menu 的 Menu.Item 控制 Content 部分的变化
  5. 阿里云 qW3xT.4 挖矿病毒问题
  6. ESP8266 ESP-01调试方法
  7. 阅读DMA Controller Core 官方手册
  8. Hyperledger fabric 1.3版本的安装部署(原创多机多Orderer部署
  9. python 多线程 并发socket实例
  10. linux 创建软链接