ADO.NET:更快的方式检查数据库服务器是否可访问? [英] ADO.NET: Faster way to check if the database server is accessible?

查看:190
本文介绍了ADO.NET:更快的方式检查数据库服务器是否可访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我使用此代码检查数据库是否可访问:

At the moment I am using this code to check if the database is accessible:

public bool IsDatabaseOnline(string con)
{
    bool isConnected = false;
    SQLConnection connect = null;

    try {
        connect = new SQLConnection(con);
        connect.Open();
        isConnected = true;

    } catch (Exception e) {
        isConnected = false;

    } finally {
        if (connect != null)
            connect.Close();
    }

    return isConnected;
}

这段代码工作正常,但有一个缺点。如果服务器不在线,则在决定不可用之前花费大约4秒钟来尝试打开连接。

While this code works fine, there is a disadvantage. If the server is not online it spends about 4 full seconds trying to open the connection before deciding that it is not available.

有没有办法测试连接而不尝试实际打开它并等待超时?类似于ping的数据库等同于

Is there a way to test the connection without trying to actually opening it and waiting for the timeout? Something like a database-equivalent of ping?

推荐答案

您可以将连接超时更改为更短。做一些测试,看看你能走多远,仍然可靠。我敢打赌你可以接近500毫秒。

You could just change the connection timeout to be shorter. Do some testing and see how low you can go and still be reliable. I bet you could get close to 500ms.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx

这篇关于ADO.NET:更快的方式检查数据库服务器是否可访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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