MjeOsX
MjeOsX

Reputation: 405

C# Persistent Connection To SQL Server

I am programming a C# TCP service. In this service clients connects to our TCP server to gets or writes some data.

The problem:

In the morning we restart our database server and the service loses the connection to the database. When the next request comes in our system there is no database connection anymore.

Does somebody knows what I can do?

How can I keep or reconnect to the database server after the restart?

Upvotes: 0

Views: 3533

Answers (1)

Larry
Larry

Reputation: 18031

In your case, I think it is better not to maintain an open SqlConnection to the sql database during all the service lifetime.

Instead, instanciate a SqlConnection object, open it, process your query, then close it: it will use the internal connection pooling mechanism of SQL server.

For example, you can enclose each queries in a block of code that Opens and Closes the connection :

using(var cn = new SqlConnection(csString))
{
    cn.Open();

    ... // your query

    cn.Close();
}

By this way, when the database restarts nightly, it will be transparent for you.

Upvotes: 2

Related Questions