在C#是什么,以确定是否数据库启动并运行的最佳方法是什么? [英] In C# what is the best way to determine if a database is up and running?

查看:138
本文介绍了在C#是什么,以确定是否数据库启动并运行的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了下面的方法来确定是数据库启动和运行。这改掉打开一个数据库连接,如果失败,返回false。

I have come up with the following method to determine is a database is up and running. This trys to open a database connection and if it fails it return false.

private static bool IsDatabaseConnectionUp(string connectionString)
{
    System.Data.SqlClient.SqlConnection conn = null;

    try
    {
        conn = new SqlConnection(connectionString);

        conn.Open();

        return conn.State == System.Data.ConnectionState.Open;
    }
    catch (SqlException)
    {
        // There was an error in opening the database so it is must not up.
        return false;
    }
    finally
    {
        if (conn != null)
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }

            conn.Dispose();
        }
    }
}

这是确定该数据库是由最好的方法是什么?我不喜欢这种方法,将依靠超时值,并会采取只要超时设置的原因。

Is this the best way to determine if this database is up? The reason I do not like this method it will rely on the timeout value, and will take as long as the timeout is set.

有没有更好的办法?

推荐答案

这真的取决于你正在努力到底该怎么确定。如果你是真正的寻找,以确定是否服务器正在运行,并能够访问,那么我会说,这是最有可能是最有效的方式。我这样说的原因是服务器本身可能是,但它可能不会接受连接,或应用程序正在使用可能是无效的(不正确的用户名/密码)的连接。

This really depends on exactly what you are trying to determine. If you are truly looking to determine if "The server is running, and able to be accessed", then I would say that this is most likely the most effective manner. The reason I say this is that the server itself could be up, but it might not be accepting connections, OR the connection that the application is using might be invalid (Incorrect username/password).

因此​​,考虑到这一点,超时是需要的东西,只要你想验证真实的连接。如果你想简单地查看服务器是否在那里,你可以尝试ping命令,但只是告诉你,如果该设备是活动的,不一定是如果SQL Server完全启动和运行,并且可用。

Therefore, given this, the timeout is a needed thing, as you want to validate true connection. If you want to simply see if the server is there, you could try pinging, but that simply tells you if the device is active, not necessarily if SQL Server is fully up and running, and available.

这篇关于在C#是什么,以确定是否数据库启动并运行的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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