In short: You should create,open,use,close,dispose Connections where you’re using them.
The best way is to use the
using-statement. By not closing the connection as soon as possible, the Connection-Pool needs to create new physical connections to the dbms which is very expensive in terms of perfomance.
Using conn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString) Using insertCommand As New SqlClient.SqlCommand("disp_banner_byPageName_views", conn) insertCommand.CommandType = CommandType.StoredProcedure ' .... End Using End Using
Performance problems are the least you get when not closing connections properly.
Edit: I’ve overlooked the
ConnectionToFetch.Close in the middle of the code.
But anyway, you should use using or the
finally of a try/catch to close a connection, otherwise it’ll keep open in case of any exceptions. Because you’ve already a try/catch you could use it to close it in it’s finally block.
I don’t want to nag even more, but an empty catch is bad, because you’ll never know when an exception was raised. You might want to log or at least
throw it again there to catch it in
Application_Error and/or in a custom error page or at the caller of this method.
Try ' code here Catch ex As Exception ' log exception and/or throw(what is always better than to intercept it) Throw Finally ConnectionToFetch.Close End Try