.net - Does SqlCommand.Dispose close the connection? -


can use approach efficiently?

using(sqlcommand cmd = new sqlcommand("getsomething", new sqlconnection(config.connectionstring)) {     cmd.connection.open();     // set parameters , commandtype storedprocedure etc. etc.     cmd.executenonquery(); } 

my concern : dispose method of sqlcommand (which called when exiting using block) close underlying sqlconnection object or not?

no, disposing of sqlcommand not effect connection. better approach wrap sqlconnection in using block well:

using (sqlconnection conn = new sqlconnection(connstring)) {     conn.open();     using (sqlcommand cmd = new sqlcommand(cmdstring, conn))     {         cmd.executenonquery();     } } 

otherwise, connection unchanged fact command using disposed (maybe want?). keep in mind, connection should disposed of well, , more important dispose of command.

edit:

i tested this:

sqlconnection conn = new sqlconnection(connstring); conn.open();  using (sqlcommand cmd = new sqlcommand("select field table fieldid = 1", conn)) {     console.writeline(cmd.executescalar().tostring()); }  using (sqlcommand cmd = new sqlcommand("select field table fieldid = 2", conn)) {     console.writeline(cmd.executescalar().tostring()); }  conn.dispose();   

the first command disposed when using block exited. connection still open , second command.

so, disposing of command not dispose of connection using.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -