Re: question about open and close of MySqlConnection
Posted by: Fernando Gonzalez Sanchez
Date: September 12, 2014 05:19PM

Hi, personally I think it is better to put the con.Close() in the finally, so it will be always executed besides if there was an exception.

Of course if the con.Open() was also in the try block, you need to check that the connection is really opened before closing it.

something like
if( ( con.State & ConnectionState.Open ) != 0 )
con.Close();

As for closing the connections sooner than later, yes, that's better.
Remember the MySqlConnection (managed resource) points to an unmanaged resource (MySql server connection).
And the server can also get saturated of open connections (that are no longer used in .NET).
If you don't explicitly close the connection, it will eventually be closed when is garbage collected.

For example, the following query will give you the list of open connections;
show processlist;

The Id column is the same value than the MySqlConnection.ServerThread property.

Now, if you plan the run more queries in the same MySqlConnection object, better keep it open (there's a small overhead in opening/closing connections).
Better yet, if you need to open/close a bunch of connections, you can enable connection pooling (so Connector/NET will keep a pool of them already open).


Thanks

*** My opinions do not necessarily reflect the opinions of my employeer ***
Fernando Gonzalez Sanchez
Sr. Software Engineer
MySql Connector/NET Team
Oracle Corporation

Options: ReplyQuote


Subject
Written By
Posted
Re: question about open and close of MySqlConnection
September 12, 2014 05:19PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.