我现在想要在程序开始启动时,检查数据库是否能够正常连通。如果连不通,希望能够在最短的时间内给出回复,现在没有做任何处理的数据库连接,当数据库连接失败时,反应好慢,需要等待好长时间;好像在数据库连接设置里面有一个TimeOut属性,可以设置数据库连接失败的等待时间,请问应该如何设置?用什么样的方式去检查数据库连接是否正常比较高效,用时比较短?因为我现在在程序连接时,不仅要检查本地的数据库是否能够正常连接,还要去检查一个远程的数据库是否能够连接,所以要求不能等待太长时间。请问有什么好的方法吗?

解决方案 »

  1.   

    参考:public DataTable GetDataTable(SqlCommand sqlCommand)
    {
        ChangeNullToDBNullValue(sqlCommand);
        bool useDefaultConnection = false;
        if (sqlCommand.Connection == null)
        {
            useDefaultConnection = true;
            sqlCommand.Connection = new SqlConnection(this.connectionString);
        }
        else
        {
            useDefaultConnection = false;
            if (sqlCommand.Connection.State != ConnectionState.Closed)
            {
                throw new ArgumentException("SqlCommand's connection state must be closed.");
            }
        }    sqlCommand.Connection.Open();
        sqlCommand.CommandTimeout = 200;
        System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
        DataTable dt = new DataTable();
        da.SelectCommand = sqlCommand;
        try
        {
            da.Fill(dt);
        }
        catch (Exception ex)
        {
            DBOperatorLogsWritter.WriteDBErrorLog(ex, sqlCommand);
        }
        sqlCommand.Connection.Close();
        if (useDefaultConnection)
        {
            sqlCommand.Connection = null;
        }
        return dt;
    }
      

  2.   

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

  3.   

    你这个不是连接的 Timeout ,而是执行的 Timeout了。