Search code examples
c#sql-serversqlconnection

Do we need open db whendb is defined in using?


when I use using for connections, I know there is no need to use close or dispose. I wonder, do we need to use open?

using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
{             
       dbSqlConnection.Open();  // is this required?
}

Solution

  • It depends on what you're doing...if you're manually executing a command using the SqlCommand object you will definitely need to open the connection before you execute any methods on the command. However, if you're using something like DataAdapter...you don't have to because it will manage the connection for you.

    Using the SqlCommand object...

    using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
    {             
           var cmd = new SqlCommand("Your_Sql_Query", con);
           dbSqlConnection.Open();  // is this required?
           cmd.ExecuteNonQuery();
    }
    

    using a SqlDataAdapter...

    using (var dbSqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString1"]))
        { 
            DataSet ds = new DataSet();
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand(
                queryString, dbSqlConnection );
            adapter.Fill(ds);
        }
    

    Notice that the SqlDataAdapter will manage the connection for you, it will open and dispose it