简体   繁体   English

在C#中,确定数据库是否已启动并正在运行的最佳方法是什么?

[英]In C# what is the best way to determine if a database is up and running?

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. 这会尝试打开数据库连接,如果失败,则返回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. 我不喜欢这种方法的原因将取决于超时值,并且只要设置了超时就需要花费时间。

Is there a better way? 有没有更好的办法?

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). 我说这的原因是服务器本身可能已启动,但它可能不接受连接,或者应用程序正在使用的连接可能无效(用户名/密码不正确)。

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. 如果您只想查看服务器是否在那儿,则可以尝试ping通,但这只是告诉您设备是否处于活动状态,并不一定告诉您SQL Server是否已完全启动并运行并且是否可用。

Since you're specifically looking at a SQLServer connection, take the connection string into a SqlConnectionStringBuilder object and change the timeout value. 由于您专门查看SQLServer连接,因此将连接字符串带到SqlConnectionStringBuilder对象中并更改超时值。

SqlConnectionStringBuilder csb = 
   new SqlConnectionStringBuilder(connectionString);
csb.ConnectTimeout = 5;
string newConnectionString = csb.ToString();

This way you control the timeout value. 这样,您可以控制超时值。 Remember, don't set it too low or you'll get false positives. 请记住,不要将其设置得太低,否则会产生误报。

Your pattern is close but there is one problem with it. 您的模式很接近,但是有一个问题。 Because SQLConnection implements IDisposable, you really should be disposing of your test connection before you return it. 由于SQLConnection实现IDisposable,因此在返回测试连接之前,您确实应该对其进行处理。

try
    {
        using (System.Data.SqlClient.SqlConnection 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;
    }

As to what the other posters said, if all you want to do is see if a database instance is running you may be able to enumerate the processes on the system, or use a command line access to test the database, but either of those options is entirely dependent on the database vendor. 至于其他发布者所说的,如果您只想查看数据库实例是否正在运行,则可以枚举系统上的进程,或者使用命令行访问来测试数据库,但是可以选择其中的一种完全取决于数据库供应商。 Your method is generally ok for most applications. 对于大多数应用程序,您的方法通常是可以的。

如果您对特定数据库(而不是整个数据库服务器)的状态感兴趣,那么可以,那将是最好的方法。

If your worried about the timeout, there are a few things you could try ... 如果您担心超时,可以尝试以下方法...

You could try and ping the server. 您可以尝试ping服务器。 Unless ICMP packets are disallowed, this will tell you more quickly if your server is down. 除非禁止ICMP数据包,否则这将在服务器关闭时更快地告诉您。 If you can't ping, you can't connect. 如果无法ping通,则无法连接。 Obviously it's no guarantee that you can connect, but it will make things quicker when you can't. 显然,这不能保证您可以连接,但是当您不能连接时,它将使事情更快。

You could use a different connection string for your server up connection test. 您可以为服务器启动连接测试使用其他连接字符串。 You generally don't need the full default time to make a connection, so you could probably lower it substantially. 通常,您不需要完整的默认时间即可建立连接,因此您可以大幅降低连接时间。

If you can allow for slightly stale data, you could have a service that goes and checks the connection every X minutes (5 or 10 or whatever) and then go an ask that service for the most recent information. 如果您可以提供稍微陈旧的数据,则可以使用一项服务,每隔X分钟(5或10分钟或其他时间)检查一次连接,然后向该服务询问最新信息。 That is more like how a Witness acts. 这更像是证人的行为。

That may be a simplified code snippet, but shouldn't you have a conn.Dispose() or using(...) {...} statement? 那可能是一个简化的代码片段,但是您不应该拥有conn.Dispose()或using(...){...}语句吗?

Edit: nevermind, I see the comments. 编辑:没关系,我看到了评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在c#中确定程序员是通过IDE还是用户运行程序的最佳方法是什么? - What is the best way in c# to determine whether the programmer is running the program via IDE or it's user? 在C#中,确定小数是否为“ int”的最佳方法是什么? - In C#, what is the best way to determine if a decimal “is an int”? 在 C# 中确定会话变量为 null 或为空的最佳方法是什么? - What is the best way to determine a session variable is null or empty in C#? C#确定继承接口类的最佳方法是什么? - C# What is the best way to determine the type of an inherited interface class? 在C#中用大写字母分割字符串的最佳方法是什么? - What is the best way of splitting up a string by capital letters in C#? 在 c# 中放大条形码图像的最佳无损方式是什么 - What is the best lossless way to scale up a barcode image in c# 从c#批量数据库插入的最佳方法是什么? - What’s the best way to bulk database inserts from c#? 从 C# 连接和使用 sqlite 数据库的最佳方法是什么? - What is the best way to connect and use a sqlite database from C# 我通过 C# 连接到离线数据库的最佳方式是什么 - What is the best way for me to connect to a offline database through C# 在C#中处理多个数据库连接的最佳方法是什么? - What is the best way to handle multiple database connections in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM