Anyone know what the best practice is for closing connections in Regular ASP, should I do it immediately after each sql query or just at the bottom of the page?
For instance, is this OK:
sql = "SELECT COUNT(*) AS num FROM tblUSER"
set rstemp = connTemp.execute(sql)
theCount = rstemp("num")
sql = "SELECT COUNT(*) AS num2 FROM tblCUSTOMER"
set rstemp = connTemp.execute(sql)
theCount2 = rstemp("num2")
rstemp.close
set rstemp = nothing
or should I close the connection after each connection like this:
sql = "SELECT COUNT(*) AS num FROM tblUSER"
set rstemp = connTemp.execute(sql)
theCount = rstemp("num")
rstemp.close
set rstemp = nothing
sql = "SELECT COUNT(*) AS num2 FROM tblCUSTOMER"
set rstemp = connTemp.execute(sql)
theCount2 = rstemp("num2")
rstemp.close
set rstemp = nothing
(If we close the connection after each query, will it use more or less resources, will it increase or decrease locks, etc)
To disconnect the connection after the query completes, from the menus go to Tools > Options > Query Execution > SQL Server > Advanced and select "Disconnect after the query executes". By checking this option, after the query executes the database connection will be disconnected.
If you do not close your database connections, many problems can occur like web pages hanging, slow page loads, and more. Think of it as going through a door to your house. Maybe the door will shut by itself, but maybe it won't. If it doesn't shut, who knows what will happen.
If you open the connection and don't close it, then it would decrease the connection pools and limits available for connecting to database again. It is always recommended to close the connection and data reader objects explicitly when you use them.
Yes, it will; the implementation of DbConnection. Dispose() calls Close() (and so do its derived implementations).
The general rule of thumb is to re-use as much as possible. Closing and reopening the connection for each query will increase your overhead unnecessarily and also possibly create issues with the connection pooling (if your are running lots and lots of queries in a short space of time.)
Hope this helps. Dave
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With