2012-07-15 38 views
7

我創造了這個方法來檢查表中的 這個記錄的數目,但它給了我這個錯誤消息,當計數的值(*)爲0 我使用這個庫連接Oracle數據庫由於對象的當前狀態,操作無效。在C#

使用Oracle.DataAccess.Client;

private int checkPort(int portID) 
     { 
      int intCount = 0; 
      try 
      { 
       OracleCommand oraCommand = new OracleCommand(); 
       oraCommand.Connection = new DBManager().getConnection(); 
       oraCommand.CommandText = "select count(*) as num from wireless_port_oid where port_id=:port_id"; 
       oraCommand.Parameters.Add(":port_id", portID); 

       OracleDataReader Reader= oraCommand.ExecuteReader(); 


       return intCount; 
       while (**Reader.Read()**)//it gives exception here 
//The err Operation is not valid due to the current state of the object. 
       { 
        intCount =Convert.ToInt32(Reader[0]); 
        Reader.Close(); 
        oraCommand.Connection.Close(); 
        oraCommand = null; 
        if (intCount > 0) 
        { 
         return 1; 
        } 
       } 
       Reader.Close(); 
       Reader.Dispose(); 
       oraCommand.Connection.Close(); 
       oraCommand.Connection.Dispose(); 
       oraCommand.Dispose(); 
       return 0; 

      } 
      catch (OracleException exception) 
      { 
       Console.WriteLine(exception.Message); 
       return 0; 
      } 
     } 
+2

那是什麼回報intCount的同時,之前在那裏做什麼? – Thousand 2012-07-15 09:34:23

+1

一些提示: 使用[ExecuteScalar](http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.executescalar%28v=vs.71%29.aspx)獲取單個值(不需要迭代/使用讀取)。你應該使用'使用'statmenet,以便你的命令等自動處理。 – 2012-07-15 09:36:06

回答

4

您正在關閉Count = 0的閱讀器,然後嘗試在while循環中再次閱讀它。

while (Reader.Read())//it gives exception here 
//The err Operation is not valid due to the current state of the object. 
       { 
        intCount =Convert.ToInt32(Reader[0]); 
        Reader.Close(); 
        oraCommand.Connection.Close(); 
        oraCommand = null; 
        if (intCount > 0) 
        { 
         return 1; 
        } 
        // if intCOunt == 0 then what? loop again 
       } 

但你的代碼是無效的 - 我只注意到你有一個回報intCount;就在你說的那一行有錯誤之前。我認爲這只是例子的錯字。

我會重構你的代碼,以C#的using語句adavantage:

private int checkPort(int portID) { 
    string sql = "select count(*) as num from wireless_port_oid where port_id=:port_id"; 
    int intCount = 0; 
    try { 
     using(OracleCommand oraCommand = new OracleCommand()) { 
      using(oraCommand.Connection = new DBManager().getConnection()) { 
       oraCommand.CommandText = sql; 
       oraCommand.Parameters.Add(":port_id", portID); 
       intCount = oraCommand.ExecuteScalar(); 
      } 
     } 
    } 
    catch (OracleException exception) { 
     Console.WriteLine(exception.Message); 
      // may be you shouldn't return 0 here possibly throw; 
    } 

    return intCount; 
} 
+0

謝謝你的幫助 – danarj 2012-07-15 11:59:22

相關問題