Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

.net - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...