是否有标准的 .NET 方法来测试 SqlConnection 字符串是否有效?

发布于 2024-10-05 20:57:48 字数 523 浏览 0 评论 0原文

可能的重复:
如何检查连接字符串是否有效?

目前我'我这样做:

internal bool CheckConnection()
{
    using (SqlConnection testConn = new SqlConnection(this.ConnectionString))
    {
        try
        {
            testConn.Open();
        }
        catch (SqlException)
        {
            return false;
        }
    }
    return true;
}

有更好的方法吗?

Possible Duplicate:
How to check if connection string is valid?

Currently I'm doing it like this:

internal bool CheckConnection()
{
    using (SqlConnection testConn = new SqlConnection(this.ConnectionString))
    {
        try
        {
            testConn.Open();
        }
        catch (SqlException)
        {
            return false;
        }
    }
    return true;
}

Is there a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自由如风 2024-10-12 20:57:48

这几乎就是做到这一点的方法。尽管您也应该考虑处理其他一些异常类型。可能还有无法连接的其他原因除了 sql 问题之外, 到数据库服务器。

除了 SqlException 之外,Connection.Open 还可以抛出 InvalidOperationException 和 ArgumentException。此外,.Open 调用的 API 可能会引发其他类型的异常,这些异常也会渗透到您的代码中。事实上,这是极少数情况之一,最好处理基本异常并向用户显示其消息。 (一般经验法则是仅处理特定的例外情况。)

That is pretty much the way to do it. Though you should think about handling some other exception types as well. There can be other reasons why you don't connect to a db server besides a sql issue.

Connection.Open can throw InvalidOperationException and ArgumentException in addition to SqlException. Also the APIs that .Open calls can throw other types of exceptions that can percolate to your code as well. In fact, this is one of the rare instances when it might be preferable to handle the base exception and display its message to the user. (The general rule of thumb is to handle only the specific exceptions.)

讽刺将军 2024-10-12 20:57:48

不,没有……这是唯一的方法

,您可以捕获 SqlException 并根据异常中的 Number 返回更多信息(如果失败)

Nop, there's not... that's the only way

What you can is catching the SqlException and return a little more info inc ase of fail depending on the Number in the exception

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文