Establish a socket connection to quickly determine whether the database connection is correct

Source: Internet
Author: User

In the project, you will often encounter the need to determine whether the database connection is successful. If you write a query statement to determine whether an error occurs during database connection, it takes a long time to return the error message. Therefore, we recommend that you first use socket to connect to the IP address of the database server and the database port on it. By default, the database server port is 1433. The code used to determine the database connection is as follows:

/// <Summary>
/// Test whether the database connection is successful
/// </Summary>
/// <Param name = "host"> Database Host Name </param>
/// <Param name = "Port"> port </param>
/// <Returns> </returns>
Public static bool testconnection (string strhost, int port)
{
VaR client = new tcpclient ();
Try
{

String host = strhost;
VaR AR = client. beginconnect (host, port, null, null );
Ar. asyncwaithandle. waitone (500 );
Return client. connected;
}
Catch
{
Return false;
}
Finally
{
Client. Close ();
}
}

The above Code only checks whether the port and IP address of the database server are accessible. If this path fails, you can directly report an error indicating a database server data source or port error.

If the above Code passes. Then, you can append the connection to open the database to determine whether the database connection string is correct to exclude the database connection string error.

The Code is as follows:

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 ();

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.