3
Reply

Closing an SqlConnection

Dy Oswald

Dy Oswald

Mar 14 2008 12:08 AM
3.4k

I don't know whether this function should (or could) be described as an 'optimized method'
Anyhow, need some advices regarding on how to close an SqlConnection without wasting too much resources

public object MethodName(){
    object retVal=new object();
    string sql="";
    SqlConnection sConn=new SqlConnection();
    SqlCommand sCmd=new SqlCommand();
    try{
        using (sConn=new SqlConnection(CONNECTION_STRING)){
            sql="SELECT * FROM [TABLE_NAME]";
            sCmd=new SqlCommand(sql, sConn);
            sConn.Open();
            try{
                retVal=sCmd.ExecuteScalar();
            }
            catch{
            }
        }
        return retVal;
    }
    catch{
        throw;
    }
    finally{
        if (sConn!=null)
            sConn.Close();
    }
}

Do I really have to put the code within the 'finally' scope?
My intention was to close the connection if there's any exception been thrown
Any advices/comments would be highly regarded


Answers (3)