Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection Pooling

I have the following code, If I use conn == null in finally do I still use connection pooling? I know it is a good practice to close your connection but how about disposing the whole connection object?

    public void ExecuteNonQuery(SqlCommand Cmd)
    {
        //========== Connection ==========//
        SqlConnection Conn = new SqlConnection(strConStr);

        try
        {
            //========== Open Connection ==========//
            Conn.Open();

            //========== Execute Command ==========//
            Cmd.Connection = Conn;
            Cmd.CommandTimeout = 180;
            Cmd.ExecuteNonQuery();
        }
        catch (Exception Exc)
        {
            throw Exc;
        }
        finally
        {
            //======== Closing Connection ========//
            if (Conn.State == ConnectionState.Open)
            { Conn.Close(); }

            //======== Disposing object ========//
            Conn = null;
        }
    }
like image 854
user291660 Avatar asked Dec 28 '22 18:12

user291660


1 Answers

First, consider using using, second, let the framework handle disposal. The managed providers will do pooling based on the connection string.

public void ExecuteNonQuery(SqlCommand Cmd) 
{ 
    //========== Connection ==========// 
    using(SqlConnection Conn = new SqlConnection(strConStr))
    { 
        //========== Open Connection ==========// 
        Conn.Open(); 

        //========== Execute Command ==========// 
        Cmd.Connection = Conn; 
        Cmd.CommandTimeout = 180; 
        Cmd.ExecuteNonQuery(); 
    } 
} 
like image 188
jball Avatar answered Dec 31 '22 13:12

jball