I have a windows service which updates data to a database table in a remote machine. I wanted to check if the service works fine after the SQL server goes down and restarts for any reason (it may be SQL server software restart or the actual windows machine rebooting abruptly).
I have installed this windows service in 10 servers. Now, when I restarted the development sql server box, all the client service programs running in all the 10 boxes were unable to reconnect. However, it works fine after I restart the client windows service.
I want the client programs to automatically reconnect once the server is available and avoid restarting them manually.
Any advise please? Thanks in advance.
Below is the code I’m using to make a connection to the sql server.
private bool ConnectToSqlServer()
{
try
{
if (sqlConnection.State == ConnectionState.Closed)
{
sqlConnection.Open();
return true;
}
return false;
}
catch(Exception Ex)
{
eventLog1.WriteEntry("ConnectToSqlServer " + Ex.Message, EventLogEntryType.Error);
return false;
}
}
SQL Server – 2008 on Windows 2008 Enterprise R2.
Client program is C#, developed in visual studio 2010, which uses .net frame work 4.
I’m assuming you’re only trying to connect once and you’re getting an exception. If you’re not then the below will not work…
Add a SqlException Catch block anywhere you access the database in your client. Then from that SqlException block invoke logic that retries to connect every x seconds for y iterations. Something like below:
Again, the retry count and wait in seconds is arbitrary for this post. You will need to take into consideration the down time of your client as it waits, and how long it normally takes for SQL Server to restart.
If you are trying the reconnect then in the SqlException block, call SqlConnection.ClearAllPools().