C# 执行多条SQL更新语句,实现数据库事务
2015-07-06 11:46
776 查看
class Program { class Result<T> { public T data; public string Message; public bool Success; public string StackTrace; } struct ExecuteableUnit { public string SQL; public SqlParameter[] param; } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> private static Result<int> ExecuteSqlTransaction(params ExecuteableUnit[] executeableUnits) { using (SqlConnection connection = new SqlConnection("")) { connection.Open(); SqlCommand command = connection.CreateCommand(); SqlTransaction transaction = connection.BeginTransaction(); command.Connection = connection; command.Transaction = transaction; int result = 0; try { foreach(ExecuteableUnit exeUnit in executeableUnits) { command.CommandText = exeUnit.SQL; if(exeUnit.param.GetLength(1) > 0) { foreach(SqlParameter p in exeUnit.param) command.Parameters.Add(p); } result += command.ExecuteNonQuery(); } transaction.Commit(); } catch (Exception ex) { // Attempt to roll back the transaction. try { transaction.Rollback(); } catch (Exception ex2) { return new Result<int>() { Success = false, Message = ex2.Message, StackTrace = ex2.StackTrace }; } return new Result<int>() { Success = false, Message = ex.Message, StackTrace = ex.StackTrace }; } finally { // Attempt to roll back the transaction. try { connection.Close(); } catch (Exception ex) { } } return new Result<int>() { Success = true, data = result }; } } public static void Main(string[] args) { } }
相关文章推荐
- 【mysql】mysql 小数转换成百分数查出(保留两位小数百分数)以及怎么使select中嵌套if的使用
- sql 中文转拼音首字母
- Android连接服务器数据库查询+Gson解析(List和Map)格式json数据(二)
- SQL -- 是否或推断线相交以在其内部的平面
- Android连接服务器数据库查询+Gson解析(List和Map)格式json数据(一)
- SQL Server游标的使用
- 看懂SqlServer查询计划
- SQL Server 中的排名函数与使用场景
- 数据库三范式
- Sql Server自增列和delete truncate删除语句关系
- 数据库进程间通信解决方案
- MySQL数据库事务隔离级别(Transaction Isolation Level)
- 数据库引擎调整顾问
- 分页查询一定范围内的SQL语句
- 利用SQL Profiler处理开销较大的查询
- SQL Server Profiler工具
- SQL Server执行计划的理解
- SQL Server Join方式
- [MySQL] - MySQL的Grant命令
- MYSQL数据库学习十七 日志管理