/// <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)方法時
發生錯誤,具體信息:" + ex.Message;
WriteLog(errorInfo);
throw ex;
}
finally
{
if (cmd.Transaction != null)
{
cmd.Transaction = null;//清空事務
}
conn.Close();
}
}
轉載自CSDN