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?
Answers. Yes. When the using block ends, the connection automatically closes (That is what IDisposable is for). So, do not close the connection explicitly.
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.
Closing the JDBC Connection This is done by calling the Connection. close() method, like this: connection. close();
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With