Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto reconnect to MySql after connection lost

I have a c# application that uses a MySql database, the problem that after a period of inactivity (8 hours) or when connection to the server where database is host is lost, the connection to the database is closed and database queries cannot be executed. how can i enable the auto reconnect to the database.

Best regards.

like image 603
DevTun Avatar asked Oct 15 '22 13:10

DevTun


2 Answers

I think the first thing that should be addressed is, why would a connection be open for 8 hours straight?

I'd think that in most cases you'll connect to the database, do your thing, and close it:

using (var conn = new MySqlConnection(connString))
{
  // do what you need here
}

The using block will create a connection which is only valid within the block. When the block ends, the Dispose method will be called on the connection and close and properly dispose of the connection object. This will prevent your application from using up available connections when they aren't needed.

If you are in a situation where you'll need to determine if the connection is open, your connection variable will have a State property which will be a ConnectionState enumeration.

You can check it using something like this:

if (conn.State != ConnectionState.Open)
{
  conn = new MySqlConnection(connString);
}

Hope that helps.

like image 73
AgentConundrum Avatar answered Oct 20 '22 14:10

AgentConundrum


In your application, before any queries, test if your connection is still active. If it isn't, then reconnect it. Et voila !

like image 38
Clement Herreman Avatar answered Oct 20 '22 15:10

Clement Herreman