What is the the best practice for SQL connections?
Currently I am using the following:
using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
sqlConn.Open();
// DB CODE GOES HERE
}
I have read that this is a very effective way of doing SQL connections. By default the SQL pooling is active, so how I understand it is that when the using code ends the SqlConnection object is closed and disposed but the actual connection to the DB is put in the SQL connection pool. Am i wrong about this?
That’s most of it. Some additional points to consider:
SqlCommand,SqlParameter,DataSet,SqlDataAdapter), and you want to wait as long as possible to open the connection. The full pattern needs to account for that..
And then write your sample like this:
That sample can only exist in your data access class. An alternative is to mark it
internaland spread the data layer over an entire assembly. The main thing is that a clean separation of your database code is strictly enforced.A real implementation might look like this:
Notice that I was also able to “stack” the creation of the
cnandcmdobjects, and thus reduce nesting and only create one scope block.Finally, a word of caution about using the
yield returncode in this specific sample. If you call the method and don’t complete yourDataBindingor other use right away it could hold the connection open for a long time. An example of this is using it to set a data source in theLoadevent of an ASP.NET page. Since the actual data binding event won’t occur until later you could hold the connection open much longer than needed.