PDA

Click to See Complete Forum and Search --> : Best way to test ms sql connection.


daimous
Jun 22nd, 2007, 05:34 PM
hi guys! I just want to know if there is a better way, than the code below, for testing the connection to my ms sql 2000 server where in i can get the specific error message and "translate" it to words that my "dumb user" can understand. Thanks in advance!


public static bool TestDBConnection(string ConnStr)
{
bool returnVal = false;
SqlConnection sqlCon = new SqlConnection(ConnStr);
try
{
sqlCon.Open();
returnVal = true;
}
catch (SqlException ex)
{
MessageBox.Show("Connection Failed!\r\nMessage: " + ex.Message, "Test Connection",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
sqlCon.Close();
}

return returnVal;
}

ComputerJy
Jun 22nd, 2007, 07:15 PM
Your code is incorrect, the finally block will try to close an unopened connection (If an exception was thrown while opening the connection) which means another exception

jmcilhinney
Jun 22nd, 2007, 08:38 PM
You should interrogate the SqlException to get specific information. It has a Errors collection whose items contain information about the specific errors that occurred on the server. It also has other properties that may be useful. You should read the MSDN documentation for the SqlException class if using it in your code, as you should for all classes you use.

Also, you should make use of a 'using' block, in which case the 'finally' block is not required:using (SqlConnection sqlCon = new SqlConnection(ConnStr))
{
try
{

}
catch
{

}
}The connection will be disposed, which inherently means closed, at the final brace. Always employ 'using' blocks for short-lived, disposable objects.

daimous
Jun 22nd, 2007, 09:32 PM
Thanks for the info guys!