Try/Finally and Connection Pooling
I had a BIG ‘no-duh’ moment this week. In fact I had a big reality check / wake-up call / whatever else you want to call it.
I wrote some horrible horrible horrible code that really was almost sinful in nature. So, first we’ll start with the (almost) forgivable mistake:
cn.connectionstring = “blah blah blah”
cmd.connection = cn
cn.open
‘database code here
cn.close
Okay… the problem there? No error handling… so if the ‘database code here’ chunk throws an error, we have a hanging connection and with connection pooling, that will hold up a resource for a LOOOOOOOOONG time.
Okay now for the even worse issue that I almost don’t want to admit:
cn.connectionstring = “blah blah blah”
cmd.connection = cn
cn.open
‘database code here
That is what I found in like 8 places in my code… no .Close called on ANY of the connections… what the heck?
The code is now fixed as it should have been done from the beginning:
cn.connectionstring = “blah blah blah”
cmd.connection = cn
cn.open
try
‘database code here
finally
cn.close
end try
Sorry for the somewhat useless spammy post but I was so mad at myself for doing either of these things… especially the latter… that I had to share.