Obtain the Query/CommandText that caused a SQLException

微笑、不失礼 提交于 2019-12-17 16:44:09

问题


I've got a logger that records exception information for our in house applications.

When we log SQL exceptions it'd be super useful if we could see the actual query that caused the exception.

Is there a way we can achieve this?


回答1:


The SqlException does not hold a reference to the SqlCommand that caused the exception. In your logger there is no way to do this. What you could do is catch the SqlException in the method that executes the SqlCommand and wrap it in a more descriptive exception. Example:

using (var command = new SqlCommand(connection, "dbo.MyProc"))
{
    try
    {
        command.Execute();
    }
    catch (DbException ex)
    {
        throw new InvalidOperationException(ex.Message + " - " + command.Text, ex);
    }
}

This way you can log this more expressive exception.




回答2:


You can NOT throw a sql exception. I think he meant to throw a new Exception that contains the command.CommandText.




回答3:


The DRYest way to do this is to write a helper method that takes a delegate, the sql command text, and optionally a sql parameter array if you're using parameterized queries. Wrap the delegate in a try catch block and call the LogError method when there is an exception:

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;
    }
} 

In my SQL code I call ExecuteAndLogError from data layer helper methods. All of the data layer methods call ExecuteAndLogError, so there is only one section of code to log SQL errors.

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;

}

You can use it like this: repo.ExecuteDataTable("SELECT * FROM Users"); If there is an exception you can implement the LogError method to perform additional logging.

Some of this code was taken from the Subtext Blog data layer classes.



来源:https://stackoverflow.com/questions/2964838/obtain-the-query-commandtext-that-caused-a-sqlexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!