I am currently working on a C# (.NET) project which connects to a MySQL Community Server database and runs some queries. There are currently 4 classes which use their own MySQLConnection object (I’m using the MySQL .NET connector), in order to connect to the database.
Is this good practice, or should I use one ‘global’ (static?) connection? Using one single connection is kind of against my habits of structuring the code. Not a big fan of 100000 objects working with one shared static field. I bet it’s against most programmers’ views too.
I also noticed that once I call connection.Close(), the connection does not necessarily get closed. Trying to .Open() it again would result in an exception. I trust this is because I did not set “Pooling=False” in the connection string. I’ll experiment with it. If you have any thoughts on this one too, feel free to drop them here.
So, in short, I’d like some opinions on how to organize my MySQLConnections. If you think a single static MySQLConnection to be used by all of the program’s classes is better (not necessarily performance-wise, I’m talking more about the effect of multiple MySQLConnections on the database system itself), let me know why you think so.
I’m expecting for the final program to have around 10 or 15 classes, each actively querying the database.
You can continue with one connection per class. Most ADO.NET providers use connection pooling per default as you have noticed.
Closedoesn’t really close the connection but return the connection to the pool. However, you should not try toOpen()the connection again but create a new connection object.There is one downfall with using one connection per class and that’s transaction handling. Transactions can not be shared over multiple connections (unless you are using
TransactionScope).I usually prefer one connection per “session” and take in the connection in the constructor to my repository classes. (As I usually use inversion of control containers). Google a bit about Unit Of Work implementations.