Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the actual SQL that caused an SqlException in C#? [duplicate]

Possible Duplicate:
Obtain the Query/CommandText that caused a SQLException

I am working on some error handling code (using elmah) and the default setup only sends the error message. I would like to know the actual SQL that throws an error (i.e. "SELECT * FROM thisTableDoesNotExist")

This is what I have so far:

if (e.Error.Exception is SqlException)
{
    //if SQL exception try to give some extra information
    SqlException sqlEx = e.Error.Exception as SqlException;
    e.Mail.Body = e.Mail.Body + "<div>" +
                                "<h1>SQL EXCEPTION</h1>" +
                                "<b>Message</b>: " + sqlEx.Message +
                                "<br/><b>LineNumber:</b> " + sqlEx.LineNumber + 
                                "<br/><b>Source:</b> " + sqlEx.Source +
                                "<br/><b>Procedure:</b> " + sqlEx.Procedure +
                                "</div>";
}

And I would like to be able to also show the actual SQL. The database is SQL Server 2008 and SqlException is of type System.Data.SqlClient.SqlException.

like image 624
Aaron Silverman Avatar asked Jan 28 '11 22:01

Aaron Silverman


People also ask

How do I get SQL exceptions?

When such an exception occurs, an object of type SQLException will be passed to the catch clause. Gets the error number associated with the exception. Gets the JDBC driver's error message for an error, handled by the driver or gets the Oracle error number and message for a database error.

How do I fix a SQL exception error?

Syntax error in the SQL statement may result in SQL Exception. When such an exception occurs, an object of the SQLException class will be passed to the catch block. By using the information in the SQLException object, we can catch that exception and continue the program.

What is error SQL?

SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. For example, writing “UPDTE” instead of “UPDATE” will produce this type of error.


1 Answers

Not possible. You'll need to catch the exception where the SQL command was executed, and then include your command text in your own custom exception. See Obtain the Query/CommandText that caused a SQLException.

like image 65
Mike Atlas Avatar answered Oct 17 '22 06:10

Mike Atlas