繁体   English   中英

从transaction.Commit()检索SQL错误消息

[英]Retrieving SQL error message from transaction.Commit()

我有一段代码遍历应作为一个事务的一部分处理的所有SQL命令列表。 我想有一种方法来知道该事务是否成功进行错误记录和处理。 由于某种原因,此时此刻我无法看到任何实际的异常或未成功的提交。 我现在正在使用下面的代码。 尝试捕获来自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();
            }
        }
    }
}

尝试捕获SqlException

然后执行以下操作:

StringBuilder sqlErrorMessages = new StringBuilder(“ Sql Exception:\\ n”);

    foreach (SqlError error in ex.Errors)
    {
        sqlErrorMessages.AppendFormat("Mesage: {0}\n", error.Message)
            .AppendFormat("Severity level: {0}\n", error.Class)
            .AppendFormat("State: {0}\n", error.State)
            .AppendFormat("Number: {0}\n", error.Number)
            .AppendFormat("Procedure: {0}\n", error.Procedure)
            .AppendFormat("Source: {0}\n", error.Source)
            .AppendFormat("LineNumber: {0}\n", error.LineNumber)
            .AppendFormat("Server: {0}\n", error.Server)
            .AppendLine(new string('-',error.Message.Length+7));

    }

如果错误的严重性为16或更高,则只会在C#中获得异常。 如果使用的是PRINT,则.NET中不会出现异常。

如果您可以编辑引发错误代码,则将在C#中导致SqlException:

RAISERROR('Some error message',16,1)然后,您可以获取SqlException.Errors集合中的每个错误。

只是一个注释-如果您之后不直接返回,则SQL Server将在RAISERROR之后继续运行命令。 如果您不返回,可能会收到多个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM