Reputation: 3030
I want check my SQL server connection before to connect with DB, and I need to update the status of SQL Server connection in my GUI.
Here is the code I am checking SQL connection, but I couldn't able to get status frequently
Scenario :
Code:
private void timer1_Tick(object sender, EventArgs e)
{
bool Flag = false;
try
{
using (SqlConnection con = new SqlConnection(strcon))
{
con.Open();
}
}
catch (SqlException s)
{
Flag = true;
label1.Text = "Connection Not available";
}
finally
{
if (Flag == false)
{
label1.Text = "Connection Live";
}
}
}
Upvotes: 1
Views: 9456
Reputation: 46415
If there server is unavailable, your application will hang while it tries to connect. This should be run in a background worker and the status updated with a callback.
Upvotes: 1
Reputation: 300489
Wrap your connection attempt in a try..catch
(it should be using a using
statement at the very least). [The precise location of a try..catch
in your code depends somewhat on the structure of your code.]
It is unusual for an application to maintain whether a SQL Server is available. After all, it might be unavailable milliseconds after you test and display that it is available.
Upvotes: 1