Click here to Skip to main content
15,905,068 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to get the error message of sql server.

C#
string expectedQuery = GenrerateQuery();
 
SqlDataAdapter ndaGlobalClass = new SqlDataAdapter(expectedQuery, conString);



After execute this query sql server can find any kind of error message if the query is not constructed properly or there is no column or database available for this query. How can i get this error meaasge from font end using C# code?

Can anyone help me by providing some code?
Posted
Updated 1-May-14 18:03pm
v2

Same as how you handle Exceptions. Use try catch block and display the Error message or meaningful custom message
C#
Try {
   // code here
}
catch (SqlException odbcEx) {
   // Handle more specific SqlException exception here.
}
catch (Exception ex) {
   // Handle generic ones here.
}


sample from MSDN[^]

C#
public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            DisplaySqlErrors(ex);
        }
    }
}

private static void DisplaySqlErrors(SqlException exception)
{
    for (int i = 0; i < exception.Errors.Count; i++)
    {
        Console.WriteLine("Index #" + i + "\n" +
            "Error: " + exception.Errors[i].ToString() + "\n");
    }
    Console.ReadLine();
}
 
Share this answer
 
v2
If you would like to find syntax errors before executing query in real time, please use SQLParser[^] class.
 
Share this answer
 
Comments
sachi Dash 2-May-14 2:56am    
If possible then give me an example code.
Maciej Los 2-May-14 3:08am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900