Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlConnection.Close() inside using statement

I'm using this code:

    public void InsertMember(Member member)     {         string INSERT = "INSERT INTO Members (Name, Surname, EntryDate) VALUES (@Name, @Surname, @EntryDate)";          using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))         {             sqlConnection.Open();              using (SqlCommand sqlCommand = new SqlCommand(INSERT, sqlConnection))             {                 sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = member.Name;                 sqlCommand.Parameters.Add("@Surname", SqlDbType.VarChar).Value = member.Surname;                 sqlCommand.Parameters.Add("@EntryDate", SqlDbType.Date).Value = member.EntryDate;                  sqlCommand.ExecuteNonQuery();             }         }     } 

Is it wrong if I don't add sqlConnection.Close(); before disposing it? I mean. It's not showing any errors, no problems at all. Is it better to Close it first? If yes, why?

like image 660
Etrit Avatar asked Sep 03 '13 08:09

Etrit


People also ask

Does using close SqlConnection?

Answers. Yes. When the using block ends, the connection automatically closes (That is what IDisposable is for). So, do not close the connection explicitly.

Should I close SqlConnection?

If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose . Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes , the underlying connection is returned back to the connection pool.

How do I close a JDBC connection?

Closing the JDBC Connection This is done by calling the Connection. close() method, like this: connection. close();


1 Answers

No need to Close or Dispose the using block will take care of that for you.

As stated from MSDN:

The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block.

private static void OpenSqlConnection(string connectionString)  {     using (SqlConnection connection = new SqlConnection(connectionString))     {         connection.Open();         Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);         Console.WriteLine("State: {0}", connection.State);     }  } 
like image 79
Darren Avatar answered Sep 22 '22 15:09

Darren