测试ConnectionString是否能连接上数据库服务器

比如你要连接一个Sql Server服务器,你有一个connection string, 但是不知道是否是正确的,你可以这样:

 

var connection = new SqlConnection(connectionString);

connection.Open();

connection.Close();

 

如果整个过程中没有异常抛出,则说明connectionString是指向一个Sql Server的服务器。但是,如果connectionString里边的Data Source(或者Server)的值是错的,就要等很久——大约30秒——才能从connection.Open()这一句抛出异常。有没有办法让这个过程快一点呢?

 

你可以试着在connectionString里添加上: "Connection Timeout=3",这指示超时时间为3秒。但是实际上效果还是一样的,异常仍然要在30秒之后才会抛出。

 

你也可以试着用另一个线程去连接服务器,主线程在若干秒后调用该线程的 Abort()方法,但是,实验效果是行不通,因为那个线程在connection.Open()里根本出不来,无法被Abort掉。

 

最后,我的解决方法还是采用后台线程,只不过如果到期尚未成功,那就当做失败,然后把它扔到一边去,不再理它了:

 

            //采用后台线程来连接数据库,以便在服务器输入错误的情况下,不用等待很长的时间才能得到一个错误提示
            string error = null;
            var success = false;

            // ReSharper disable AccessToModifiedClosure
            // ReSharper disable UseObjectOrCollectionInitializer
            var thread = new Thread(() =>
                                        {
                                            try
                                            {
                                                connection.Open();
                                                connection.Close();

                                                success = true;
                                            }
                                            catch (SqlException ex)
                                            {
                                                error = ex.Message;
                                            }
                                            finally
                                            {
                                                if (connection.State == ConnectionState.Open)
                                                    connection.Close();
                                            }
                                        });
            // ReSharper restore AccessToModifiedClosure
            // ReSharper restore UseObjectOrCollectionInitializer
            thread.IsBackground = true;
            var sw = Stopwatch.StartNew();
            thread.Start();

            var timeout = TimeSpan.FromSeconds(3);
            while (sw.Elapsed < timeout)
                thread.Join(TimeSpan.FromMilliseconds(200));
            sw.Stop();

            if (!success)
            {
                throw new Exception(error ?? "连接数据库超时,请检查输入的服务器是否正确。");
            }

posted on 2009-11-28 14:34  deerchao  阅读(2520)  评论(0编辑  收藏  举报