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