关闭SqlConnection和SqlCommand c#

在我的DAL中,我写这样的查询:

using(SQLConnection conn = "connection string here") { SQLCommand cmd = new ("sql query", conn); // execute it blah blah } 

现在我发现我没有明确关闭SQLCommand对象。 现在我知道’using’块将处理SQLConnection对象,但这还会处理SQLCommand对象吗? 如果不是我有一个严重的问题。 我必须在SQLCommand上使用’使用’成千上万行代码,或者在数百种方法上执行cmd.Close()。 请告诉我,如果使用或关闭命令将提供更好的Web应用程序内存管理?

不, using语句不会处理命令。

您也应该using语句包装命令,因为这将正确调用Dispose

 using(SQLConnection conn = 'connection string here') { using(SQLCommand cmd = new ('sql query', conn)) { //execute it blah blah } } 

SqlConnection不了解SqlCommand ,因此您应该自行关闭它:

 using (SqlConnection conn = new SqlConnection("connection string here")) using (SqlCommand cmd = new SqlCommand("sql query", conn)) { // execute it blah blah } 

它不会处理SqlCommand ,但SqlCommand 最终将由垃圾收集器处理。 我倾向于做以下事情:

 using (SqlConn conn ... ) using (SqlComm comm ... ) { conn.Open(); } 

在这里堆叠using语句将处理两者。