Using Statements to wrap your database connections

In yesterday’s piece entitled Using Regular Expressions (Regex) to find all your SqlConnection strings I wrote about the fact I was trying to use  a regex string to find all my SqlConnection declarations.

In the piece I made mention of the fact that the using statement are becoming the defacto way of wrapping your connections. I first heard about this in the James Michael Hare series of articles C#/.NET Little Wonders – All The Wonders In Their Glory

The using statement is not the same as the using declarations at the top of your code behind files. Instead, they are used to wrap pieces of code so that they will call IDisposable as soon as they go out of scope.

So, instead of forgetting to call dispose on your SqlConnection instances and running the chance of having some connection pooling issues, we can use the following to instantiate our objects:

using statement

As you can see I have wrapped the code in a using block with both brackets and curly braces. I don’t have to use any try/catch statements nor do I have to explicitly dispose of my connection object. The using statement will call the Dispose() method as soon as it is out of scope – either when it completes or if it encounters an error.

So, check out using statements. They will make sure you never have to worry about closing out your connection strings and they will make your code a little bit neater.

Advertisements

About Ken Cenerelli
I am a Programmer Writer, .NET Developer, Microsoft MVP - Visual Studio and Development Technologies, Public Speaker, Blogger, and Microsoft Azure Nerd. I blog regularly at kencenerelli.wordpress.com and can be found on Twitter via @KenCenerelli.

2 Responses to Using Statements to wrap your database connections

  1. Lee says:

    Ken, does .Net do this automatically when using declarative code with a SqlDataSource?

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: