sql server - Disposing the Sql Connection -
Just wondering, can SQL Connection be dipped / stopped when this method is completed? Or do I have to explicitly call the closing method in the end? Using
(SqlCommand cmd = new SqlCommand (sql, GetConnection ())) {SqlDataReader reader = cmd.ExecuteReader (); While (reader.Read ()) {}} SqlConnection GetConnetion () {New SqlConnection ("connectionstring"); }
I know that I can do something like this:
SqlConnection conn = GetConnetion (); SqlCommand CMD = New SQL Commands (Esquilla, Con); // something conn.Close () cmd.Dispose ()
But just curious how to use block will work in this case. Cheers
No, the connection object will not be automatically removed in your example. The Usage
block only applies to the SqlCommand
object, not the connection.
To make sure that the connection has been resolved, make sure that block
in its own using the
SqlConnection
object: Using p>
(using SqlConnection conn = GetConnection ()) (SqlCommand cmd = new SqlCommand (sql, Conn)) // {actually using it conn.Open () Do not forget to open the connection before; ({Reader.Read ()} {// do something}}}
Comments
Post a Comment