由于对象的当前状态,操作无效.在C#中

前端之家收集整理的这篇文章主要介绍了由于对象的当前状态,操作无效.在C#中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了这个方法来检查表中这条记录的编号
但是当count(*)的值为0时,它会给我这个错误消息
我用这个库来连接oracle db

使用Oracle.DataAccess.Client;

  1. private int checkPort(int portID)
  2. {
  3. int intCount = 0;
  4. try
  5. {
  6. OracleCommand oraCommand = new OracleCommand();
  7. oraCommand.Connection = new DBManager().getConnection();
  8. oraCommand.CommandText = "select count(*) as num from wireless_port_oid where port_id=:port_id";
  9. oraCommand.Parameters.Add(":port_id",portID);
  10.  
  11. OracleDataReader Reader= oraCommand.ExecuteReader();
  12.  
  13.  
  14. return intCount;
  15. while (**Reader.Read()**)//it gives exception here
  16. //The err Operation is not valid due to the current state of the object.
  17. {
  18. intCount =Convert.ToInt32(Reader[0]);
  19. Reader.Close();
  20. oraCommand.Connection.Close();
  21. oraCommand = null;
  22. if (intCount > 0)
  23. {
  24. return 1;
  25. }
  26. }
  27. Reader.Close();
  28. Reader.Dispose();
  29. oraCommand.Connection.Close();
  30. oraCommand.Connection.Dispose();
  31. oraCommand.Dispose();
  32. return 0;
  33.  
  34. }
  35. catch (OracleException exception)
  36. {
  37. Console.WriteLine(exception.Message);
  38. return 0;
  39. }
  40. }

解决方法

您在Count = 0时关闭读取器,然后尝试在while循环中再次读取它.
  1. while (Reader.Read())//it gives exception here
  2. //The err Operation is not valid due to the current state of the object.
  3. {
  4. intCount =Convert.ToInt32(Reader[0]);
  5. Reader.Close();
  6. oraCommand.Connection.Close();
  7. oraCommand = null;
  8. if (intCount > 0)
  9. {
  10. return 1;
  11. }
  12. // if intCOunt == 0 then what? loop again
  13. }

但是你的代码无效 – 我只是注意到你有一个返回intCount;就在您说的行之前有错误.我认为这只是一个错误的例子.

我会重构你的代码以利用C#的using语句:

  1. private int checkPort(int portID) {
  2. string sql = "select count(*) as num from wireless_port_oid where port_id=:port_id";
  3. int intCount = 0;
  4. try {
  5. using(OracleCommand oraCommand = new OracleCommand()) {
  6. using(oraCommand.Connection = new DBManager().getConnection()) {
  7. oraCommand.CommandText = sql;
  8. oraCommand.Parameters.Add(":port_id",portID);
  9. intCount = oraCommand.ExecuteScalar();
  10. }
  11. }
  12. }
  13. catch (OracleException exception) {
  14. Console.WriteLine(exception.Message);
  15. // may be you shouldn't return 0 here possibly throw;
  16. }
  17.  
  18. return intCount;
  19. }

猜你在找的C#相关文章