如何获取sql server的错误信息? [英] How can I get the error message of sql server ?

查看:150
本文介绍了如何获取sql server的错误信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取sql server的错误信息。



I want to get the error message of sql server.

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







执行此查询后,如果查询构造不正确或者此查询没有可用的列或数据库,sql server可以找到任何类型的错误消息。如何使用C#代码从字体结尾获取此错误?



任何人都可以通过提供一些代码来帮助我吗?




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?

推荐答案

与处理异常的方式相同。使用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.


这篇关于如何获取sql server的错误信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆