By establishing a Socket connection to quickly determine whether the correct database connection

           Often encounter in the project to determine if the database connection is successful. If you write a query to judge, the database connection error when it will take a long time to return an error message. Therefore, it is recommended to use the Socket IP port to connect to the database and on the database server. Ports for the database server 1433. By default, database connection code is determined as follows:

        /// <the Summary>
        /// test the database connection is successful
        /// </ the Summary>
        /// <param name = "Host"> database hostname </ param>
        /// <param name = "Port"> port </ param>
        /// <Returns> </ Returns>
        public static BOOL TestConnection (String strHost, int port)
            {
            var = new new Client the TcpClient ();
            the try
                {
                
                String Host = strHost;
                var client.BeginConnect Ar = (Host , Port, null, null);
                ar.AsyncWaitHandle.WaitOne (500);
                return client.Connected;
                }
            catch
                {
                return false;
                }
            finally
                {
                client.Close();
                }
            }

The above code only judge the port and IP database server whether this road is through. If that road leads nowhere, you can direct error prompt the database server or data source port is wrong.

If the above code is adopted. You can then open the additional connection to the database to determine whether the correct connection string database, the database is connected to eliminate the error string.

code show as below:

 public static bool TestConnection(string ConnectionString)
        {
            bool result = true;

           SqlConnection m_myConnection = new SqlConnection(ConnectionString);
            try
            {
                m_myConnection.Open();

                return result;
               
            }
            catch
            {
                result = false;

                return result;
            }

            finally

           {

                m_myConnection.Close();

          }           

        }







Reproduced in: https: //www.cnblogs.com/kevinGao/archive/2011/11/03/2236174.html

Guess you like

Origin blog.csdn.net/weixin_33872566/article/details/93361098