具体代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/// <summary>
/// 启用事务提交多条带参数的SQL语句
/// </summary>
/// <param name="mainSql">主表SQL</param>
/// <param name="mainParam">主表对应的参数</param>
/// <param name="detailSql">明细表SQL语句</param>
/// <param name="detailParam">明细表对应的参数</param>
/// <returns>返回事务是否成功</returns>
public static bool UpdateByTran( string mainSql, SqlParameter[] mainParam, string detailSql, List<SqlParameter[]> detailParam)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
try
{
conn.Open();
cmd.Transaction = conn.BeginTransaction(); //开启事务
if (mainSql != null && mainSql.Length != 0)
{
cmd.CommandText = mainSql;
cmd.Parameters.AddRange(mainParam);
cmd.ExecuteNonQuery();
}
foreach (SqlParameter[] param in detailParam)
{
cmd.CommandText = detailSql;
cmd.Parameters.Clear();
cmd.Parameters.AddRange(param);
cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit(); //提交事务
return true ;
}
catch (Exception ex)
{
if (cmd.Transaction != null )
{
cmd.Transaction.Rollback(); //回滚事务
}
//将异常信息写入日志
string errorInfo = "调用UpdateByTran(string mainSql, SqlParameter[] mainParam,string detailSql ,List <SqlParameter []>detailParam)方法时<br data-filtered=" filtered ">发生错误,具体信息:" + ex.Message;
WriteLog(errorInfo);
throw ex;
}
finally
{
if (cmd.Transaction != null )
{
cmd.Transaction = null ; //清空事务
}
conn.Close();
}
}
|
总结
以上所述是小编给大家介绍的C# 启用事务提交多条带参数的SQL语句,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.cnblogs.com/ZeedLee/archive/2018/02/28/8482185.html