且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取sql server的错误信息?

更新时间:2022-03-23 10:25:50

与处理异常的方式相同。使用try catch块并显示错误消息或有意义的自定义消息

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





来自 MSDN [ ^ ]





sample from MSDN[^]

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


如果您想在实时执行查询之前发现语法错误,请使用 SQLParser [ ^ ] class。
If you would like to find syntax errors before executing query in real time, please use SQLParser[^] class.