2010-07-30 81 views
14

在我DAL我編寫查詢這樣的:關閉的SqlConnection和SqlCommand的C#

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

現在它只是發生在我身上,我沒有顯式關閉SqlCommand對象。現在我知道「使用」塊將處理SQLConnection對象,但這是否也會照顧SQLCommand對象?如果不是,我有一個嚴重的問題。我必須在成千上萬行代碼中使用SQLCommand中的「使用」,或者對數百種方法執行cmd.Close()。請告訴我,如果使用或關閉命令將提供更好的Web應用程序的內存管理?

+0

我想這也應該是有趣的你:http://valueinjecter.codeplex.com/ WIKIPAGE?標題=數據%20access%20layer%20%28ORM%29%20with%第二十條%20Value%20Injecter&referringTitle =首頁 – Omu 2010-07-30 11:37:55

回答

9

不,using聲明不會處理該命令。

你應該換用using語句命令爲好,因爲這會正確地調用Dispose他們:

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

SqlConnection沒有關於SqlCommand知識,所以你應該自行關閉:

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

它不會處理SqlCommand,但SqlCommand最終由垃圾收集處理。我傾向於執行以下操作:

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

堆棧使用語句在這裏將處理這兩個。

相關問題