我有一段代码,它迭代一组SQL命令,这些命令应该作为一个事务的一部分进行处理。我希望有一种方法来了解该事务是否成功,以便进行错误记录和处理。在这个时刻,由于某种原因,我在看到任何类型的实际异常或不成功的提交时遇到了问题。我现在正在使用下面的代码。try catch来自MSDN页面推荐。请随时在这里戳任何其他漏洞,你可以看到,不是100%对我的问题。这些都是存储的proc类型的SqlCommands的命令,并在将其添加到SQL命令列表之前添加了参数。
public static async Task UpdateSQL(string inputQuery,
string inputId, List<SqlCommand> commandList, TraceWriter log)
{
try
{
string str = ConfigurationManager.ConnectionStrings
["connString"].ConnectionString;
log.Info($"Running query: {inputQuery}");
int commandRows = 0;
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
SqlTransaction tr = conn.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand(inputQuery, conn);
cmd.Transaction = tr;
foreach (var command in commandList)
{
command.Connection = conn;
command.Transaction = tr;
log.Info($"{command.CommandText} query running"); //last log output if unsuccesful (based on end result in database)
commandRows += await command.ExecuteNonQueryAsync();
}
log.Info($"total rows updated: {commandRows}");
tr.Commit();
conn.Close();
}
catch(Exception ex)
{
Console.WriteLine($"Commit Exception Type: {ex.GetType()}");
Console.WriteLine($" Message: {ex.Message}");
try
{
tr.Rollback();
conn.Close();
log.Info($"{inputId} transaction rolled back");
}
catch (Exception ex2)
{
// rollback fail Exception
log.Info($"Rollback Exception Type: {ex2.GetType()}");
log.Info($" Message: {ex2.Message}");
conn.Close();
}
}
}
}
https://stackoverflow.com/questions/50768977
复制相似问题