【问题标题】:How to check if OleDbDataReader is empty?如何检查 OleDbDataReader 是否为空?
【发布时间】:2020-09-25 21:46:19
【问题描述】:

这是我用来根据 Class 字段值选择最大 RollNo 的代码。 但是当表中没有Class字段的数据时。然后产生Error。

using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
            {
                conn.Open();
                command = new OleDbCommand("select max(RollNo) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
                OleDbDataReader dr = command.ExecuteReader();
                if (!dr.IsDBNull(0))
                {
                    while (dr.Read())
                    {
                        i = Convert.ToInt32(dr["Roll"]);
                    }
                }

InvalidOperation 异常正在发生。如果表中有数据,我想获得 RollNo 的值。如果表中没有数据,我该怎么办?

【问题讨论】:

  • 你试图在阅读之前访问该行,if (!dr.IsDBNull(0))
  • 那我该怎么办?
  • 为了你自己,请使用参数而不是字符串连接
  • 我将使用 now 参数

标签: c# database ms-access oledbdatareader


【解决方案1】:

你正在颠倒步骤:

  • 打开连接;
  • 检查是否有数据;
  • 检查值是否不为空;
  • 读取数据;

试试这个:

while (dr.Read())
   {
       if (!dr.IsDBNull(0))
          {
            i = Convert.ToInt32(dr["Roll"]);
          }
   }

当您只关注单个值时,使用 executeScalar 获取值;

  conn.Open();          
  command = new OleDbCommand("select isnull(max(RollNo),-1) as Roll from Students where Class = '"+cmbClass.Text+"'", conn);
  int rollNo = (int) command.ExecuteScallar();
  if(rollno !=-1)
  {
     // TODO :
  }

【讨论】:

  • if(rollno !=-2) 为什么你使用-2?
  • 当我执行你给定的代码时,它给出了 OleDbException。
  • 附加信息:查询表达式'isnull(max(RollNo),-1'中函数使用的参数数量错误。
  • 对不起兄弟,我想写{-1},我忘记了查询中的')',对不起
  • 它在这一行给出错误 [ int rollNo = (int) command.ExecuteScalar(); ] 指定的强制转换无效。
猜你喜欢
  • 2017-11-15
  • 2020-05-29
  • 2018-04-02
  • 2016-04-05
  • 2018-01-08
  • 2012-01-15
  • 2016-07-16
  • 2021-08-14
  • 2021-10-14
相关资源
最近更新 更多