获取导致SQLException的查询/命令文本

问题描述 投票:13回答:3

我有一个记录器,用于记录内部应用程序的异常信息。

当我们记录SQL异常时,如果我们可以看到导致异常的实际查询,那将非常有用。

我们有办法实现这一目标吗?

c# sqlexception
3个回答
17
投票
using (var command = new SqlCommand(connection, "dbo.MyProc")) { try { command.Execute(); } catch (DbException ex) { throw new InvalidOperationException(ex.Message + " - " + command.Text, ex); } }

通过这种方式,您可以记录这个更具表现力的异常。


2
投票

-1
投票
protected virtual TResult ExecuteAndLogError<TResult>(Func<TResult> code, string sql, SqlParameterCollection parameters = null) { try { if ((System.Diagnostics.Debugger.IsAttached)) PrintSqlToDebug(sql, parameters); return code(); } catch (Exception ex) { LogError(sql, parameters, ex); throw; } }

在我的SQL代码中,我从数据层帮助程序方法调用ExecuteAndLogError。所有数据层方法都调用ExecuteAndLogError,因此只有一段代码可以记录SQL错误。

public virtual DataTable ExecuteDataTable(SqlCommand command, params SqlParameter[] parameters)
{
    command.Parameters.AddRange(parameters);
    DataTable table = new DataTable();

    using (SqlDataAdapter adapter = new SqlDataAdapter(command)) {
        using (command) {
            ExecuteAndLogError(() => adapter.Fill(table), command.CommandText, command.Parameters);
        }
    }

    return table;

}

您可以像这样使用它:repo.ExecuteDataTable("SELECT * FROM Users");如果存在异常,则可以实现LogError方法来执行其他日志记录。

其中一些代码摘自Subtext Blog数据层类。

© www.soinside.com 2019 - 2024. All rights reserved.