Return SQL Server error to user
I want to return error that occured at the time of update in SQL Server 2008.
Now I want to display this erro开发者_高级运维r to user so that he can understand what goes wrong.
How should I do this in c#?
Thanks.........
Errors when performing an SQL statement against a database raise an exception in the connector. Those exceptions are of type SqlException and, as such, have a Message property that contains a user friendly description of the error.
Remember though that while user-friendly, this message is aimed at developers. You should not display that to an end-user.
As usual, to trap an exception you have to use a try-catch block:
try
{
SqlConnection conn = null;
conn = new SqlConnection(connString); // connstring is your connection string to the database
conn.Open();
var strSQLCommand = "SELECT* FROM TABLE"; // statement is wrong! will raise an exception
var command = new SqlCommand(strSQLCommand, conn);
var ret = command.ExecuteScalar();
conn.Close();
return ret;
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
This example of course assumes a Console application.
try this
try
{
//your sql code
}
catch(SqlException sqlEx)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
SqlException - which catches all the sql exception
Try using a try, catch clause
something like that:
try {
// Update Code Here
}
catch (Exception e) {
// Error message in e.Message
// On a form
MessageBox.Show(e.Message, "Error!");
// TextBox text1 is defined
text1.Text = e.Message;
System.Console.WriteLine(e.Message);
}
where you can replace Exception with the type of exception you want to catch (SqlException).
精彩评论