views:

339

answers:

4

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 in 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?

+1  A: 

Your understanding of using is correct, and that method of usage is the recommended way of doing so. You can also call close in your code as well.

Mitchel Sellers
Thanks. The way that i understand it that when the "using" is finished and that calles SqlConnection.Dispose(); that ultimatly calls SqlConnection.Close()
Neale
your understanding of "using" is correct as well.
David Yancey
@Neale - Yea, SqlConnection.Dispose() will call Close if it is required. If the connection was already closed it simply releases the handle back to the ado.net provider which is then free to put it in a pool or actually close it.
Jason Short
+10  A: 

That's most of it. Some additional points to consider:

  • Where do you get your connection string? You don't want that hard-coded all over the place and you may need to secure it.
  • You often have other objects to create as well before your really use the connection (SqlCommand, parameters, dataset, SqlDataApapter), and you want to wait as long as possible to open the connection. The full pattern needs to account for that.
  • You want to make sure your database access is forced into it's own data layer class or assembly. So a common thing to do is express this as a private function call:

.

private static string connectionString = "load from encrypted config file";
private SqlConnection getConnection()
{
    return new SqlConnection(connectionString);
}

And then write your sample like this:

using(SqlConnection sqlConn = getConnection())
{
    // create command and add parameters

    //open the connection
    sqlConn.Open();

   //run the command
}

That sample can only exist in your data access class. An alternative is to mark it internal and 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:

public IEnumerable<IDataRecord> GetSomeData(string filter)
{
    string sql = "SELECT * FROM [SomeTable] WHERE [SomeColumn] LIKE @Filter + '%'";

    using (SqlConnection cn = getConnection())
    using (SqlCommand cmd = new SqlCommand(sql, cn))
    {
        cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter;
        cn.Open();

        using (IDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                yield return (IDataRecord)rdr;
            }
        }
    }
}

Notice that I was also able to "stack" the creation of the 'cn' and 'cmd' objects, and thus reduce nesting and only create one scope block.

Finally, a word of caution about using the yield return code in this specific sample. If you call the method and don't complete your DataBinding or 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 the Load event 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.

Joel Coehoorn
point 1: I store my connection strings in the <connectionstring> section of the app/web.configPoint 2: Is this something i should worry about. I normally do SqlConnection, then open it, then create my sqlCommand and then take if from there.Point 3: We do all our DB access from a class lib. I dont like doing DB access form the core application. Is it worth my while to create the getConnection method??
Neale
Joel Coehoorn
+2  A: 

Microsoft's Patterns and Practices libraries are an excellent approach to handling database connectivity. The libraries encapsulate most of the mechanisms involved with opening a connection, which in turn will make your life easier.

Jagd
A: 

Also : Open late, close early.

Don't open the connection until there are no more steps left before calling the database. And close the connection as soon as you're done.

çağdaş