Guapo
Guapo

Reputation: 3482

Leave MySQL connection idle to be reused or connect on demand, what about classes?

I am currently working on a Desktop Application using winforms and .NET 4.0, I have downloaded the latest MySQL connector for .NET 4.0 but I have a few doubts of what would be the best way to go with it.

NOTE: Just want to point out this application is for personal use and will be running on my own server.

Upvotes: 3

Views: 908

Answers (1)

MarkR
MarkR

Reputation: 63538

In my view, you should open the connection at the beginning of a user action and close it at the end. This won't affect performance significantly because connecting is just as quick as doing a single query.

However, if you open/close a connection for each sub-operation, you can end up with poor performance. Be sure that you don't do that.


The main motivation for using a new connection each time, is that you can avoid the following classes of bugs:

  • "Morning" bugs where the database has disappeared or disconnected after a while (or timeouts on stateful firewalls, etc)
  • "Stale state" bugs where some previous action has left the connection in a "broken" state and causes the next action to fail or behave unexpectedly (e.g. "SET names koi8")

It is possible to reset a mysql connection by doing a mysql_change_user (If your API supports it), but this is almost the same as reconnecting (it just uses the same tcp connection).

Upvotes: 4

Related Questions