|
-
Jun 22nd, 2007, 05:34 PM
#1
Thread Starter
Fanatic Member
Best way to test ms sql connection.
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!
Code:
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;
}
-
Jun 22nd, 2007, 07:15 PM
#2
Re: Best way to test ms sql connection.
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
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Jun 22nd, 2007, 08:38 PM
#3
Re: Best way to test ms sql connection.
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:
C# Code:
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.
-
Jun 22nd, 2007, 09:32 PM
#4
Thread Starter
Fanatic Member
Re: Best way to test ms sql connection.
Thanks for the info guys!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|