I have a piece of code that iterates through a list of SQL commands that should be processed all as part of one transaction. I want to have a way of knowing if that transaction was successful for error logging and handling purposes. At this moment in time for some reason I have a problem seeing any kind of actual exception or unsuccessful commit. I am using the code below right now. The try catch is from the MSDN page recommendation. Please feel free to poke any other holes in this that you can see that are not 100% about my question. These are all commands of SqlCommands of the stored proc type with parameters added to it prior to adding it to the list of SQL commands.
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();
}
}
}
}
conn.Close()(and of them) - theusingblock will do that for you.At this moment in time for some reason I have a problem seeing any kind of actual exception or unsuccessful commit.This is unclear. Do you mean it always works and you are hoping it doesn't so you can see what happens? Or something else?so there is no need to conn.Close() anywhere in this piece of code as long as the using statement is used as it is here?Yes.