2012-07-15 24 views
7

私はテーブル にこのレコードの数を確認するには、このメソッドを作成していたが、カウントの値が(*)0 iはオラクルDBオブジェクトの現在の状態のため、操作が無効です。 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

+1

いくつかのヒント: [ExecuteScalar](http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.executescalar%28v=vs.71%29.aspx)を使用してシングル値(反復/読み込みの必要はありません)。コマンドなどが自動的に処理されるように、 'using' statmenetを使うべきです。 –

答えて

4

あなたはカウント= 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

関連する問題