Link to home
Start Free TrialLog in
Avatar of ordo
ordoFlag for United States of America

asked on

.Net and SQL Database connections

General question about .Net and SQL Database connections; When to open and close connection?

General program logic flow is -

Open DB connection
get data
Close DB connection

perform some logic

Open DB connection
get data
Close DB connection

perform some logic

repeat above necessary.

Should the DB connection be closed after each get data as in the example, or should we open the connection once, and close it at the end of the program i.e.

Open DB connection
get data

perform some logic

get data

perform some logic

get data

perform some logic

Close DB connection.

Thanks for your help.
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ordo

ASKER

Kyle,

Thanks for your response. The data 'get's are logic dependent, so open and close each time seems to be the way to go. The problem we're running into is that we get Max Connection (max of 200) errors when the webpage is getting heavy use.

Do you know if the connection is returned to the pool immediately upon closing, or is there some action we can take to facilitate that?

That being said, I am going to review the logic and code to see if we can't reduce the number of connections.

Best regards,

Pat
Your question is in the MySQL Topic Area.  If you are using the MySQL .NET connector in your application, you will find that it does some of the connection management itself.  http://dev.mysql.com/downloads/connector/net/
How many users?  It could be that you're just using up that many connections.

If you call the conn.Close() it should release that connection.

This should be easy enough to do on your local machine:

Point the .net code at a test server or on your local machine.  The idea being that you're going to be the only one connecting to it.

Set a break point after the open, after the close, and after the open again.

Right before you run the program (to get a baseline), and at each break point, run this to check the number of connections:

SHOW STATUS WHERE `variable_name` = 'Threads_connected'
     - or  - 
SHOW PROCESSLIST

Open in new window


You should see the number of connections being affected.