OledbDataReader函数返回整数

本文关键字:整数 返回 函数 OledbDataReader | 更新日期: 2023-09-27 18:02:14

在c#中工作,我遇到了一个函数的麻烦。函数运行查询,查询应该返回一个整数值,但我有问题返回它。我一直得到这样的错误:

  • 无法将oleDbDataReader类型的对象强制转换为Int32类型
  • 指定的类型转换无效

不确定如何在c#和OleDbDataReader中做到这一点。我的代码在

下面
     public static int FifthQuery()
     {
         int _value = 0;
         OleDbConnection _connectMe = Utilities.OledbConnect();
         OleDbCommand _query1 = new OleDbCommand();
         _query1.Connection = _connectMe;
         _query1.CommandText = "SELECT count(*) FROM GIS.PERSONS where Name_Prefix = 'Dr.'";
         OleDbDataReader _reader = _query1.ExecuteReader();
         _reader.Read();
              //_value = Convert.ToInt32(_reader);
              _value = _reader.GetInt32(0);

         return _value;
     }

OledbDataReader函数返回整数

既然您使用COUNT(*),那么使用ExecuteScalar将是更好的方法。

执行查询,返回中第一行的第一列查询返回的结果集合。

int _value = (int)_query1.ExecuteScalar();

也使用using语句来处理您的OleDbConnectionOleDbCommand

using(OleDbConnection _connectMe = Utilities.OledbConnect())
using(OleDbCommand _query1 = _connectMe.CreateCommand())
{
    _query1.CommandText = "SELECT count(*) FROM GIS.PERSONS where Name_Prefix = 'Dr.'";
    _connectMe.Open();
    int _value = (int)_query1.ExecuteScalar();
}