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 :
- Stop the sql server service from services window
- Running the project and will show status “Connection Not Available”
- Start Sql server service and displaying “Connection Live”
- And Again Stop SQL server service and i am not getting the status as “”Connection Not
Available”. It’s returning status as “Connection Live” - It’s not getting to the catch block
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";
}
}
}
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.