2013-06-19 45 views
0

我打電話我applciation OracleCommandd.ExecuteNonquery()和我得到「連接必須是打開此操作」在下面的代碼異常異常:「連接必須是打開此操作」上ODP

using (OracleConnection connection = new OracleConnection(ConnectionString)) 
     { 
      OracleCommand oracleCommand = new OracleCommand(procedureName, connection); 
      oracleCommand.CommandType = CommandType.StoredProcedure; 

      oracleCommand.ExecuteNonQuery(); 
     } 

當我在using語句後面放置connection.Open();時,不會發生異常,但不會發生using語句處理連接的打開和關閉階段(實際上打開close關閉連接池到連接池)。

回答

1

,但沒有使用的語句處理的開閉 連接的階段


using什麼connection.Open()

using (OracleConnection connection = new OracleConnection(ConnectionString)) 
{ 
    connection.Open(); //<-- must have 
    //rest of code omitted 
} 

你不不需要撥打connection.Close(),因爲連接處理時會發生這種情況。這是using關鍵字的真正目的。

這就是using居然翻譯成:

try 
{ 
    //code omitted 
} 
finally 
{ 
    connection.Dispose(); 
} 
3

using語句只是用於實例將在using語句的範圍內使用的對象。它會在處理連接時關閉連接,但不會打開它,您必須自己動手。 從MSDN

提供了一個方便的語法,確保正確使用 IDisposable的對象。

using (OracleConnection connection = new OracleConnection(ConnectionString)) 
    { 
      connection.Open(); 
      using (OracleCommand oracleCommand = new OracleCommand(procedureName, connection);) 
      { 
       oracleCommand.CommandType = CommandType.StoredProcedure; 
       oracleCommand.ExecuteNonQuery(); 
      } 
    } 
+0

我喜歡烏爾辦法,但你怎麼能捕捉異常,如果在所有它長大的嗎?同時使用Using語句和try catch塊是否是一個好習慣? – Biki

+0

是的,你可以用一個try-catch塊封裝所有這些。 –

相關問題