【问题标题】:SqlDataReader.HasRows return always "true" even with empty result即使结果为空,SqlDataReader.HasRows 也始终返回“true”
【发布时间】:2019-03-28 10:15:19
【问题描述】:

在浏览了大量关于SqlDataReader.HasRows 现象的主题后,即使结果为空也总是返回 true(尤其是当它是关于带有聚合的 SQL 查询时),我完全干了我的代码

但是我的示例非常简单,HasRows 返回 TrueFieldCount 返回 1,即使没有 phpMyAdmin 侧行。

query = "SELECT FK_BarId FROM tlink_bar_beer WHERE FK_BeerId = " + sqlDataReader.GetInt32(0);

MySqlConnection sqlConnexionList = new MySqlConnection("server=localhost;database=beerchecking;uid=root;password=;");
MySqlCommand commandList = new MySqlCommand(query, sqlConnexionList);
sqlConnexionList.Open();

int[] BarsIds;
using (MySqlDataReader sqlDataReaderList = commandList.ExecuteReader())
{
    if (sqlDataReaderList.HasRows)
    {
        try
        {
            BarsIds = new int[sqlDataReaderList.FieldCount];
            int counter = 0;

            if (sqlDataReaderList.Read())
            {
                while (sqlDataReaderList.Read())
                {
                    int id = sqlDataReaderList.GetInt32(counter);
                    BarsIds[counter] = id;
                    counter++;
                }
            }
        }
        finally
        {
            sqlDataReaderList.Close();
        }
    }
    else
    {
        BarsIds = new int[0];
    }
}

sqlConnexionList.Close();

你知道当 phpMyAdmin 结果中没有行时如何让 HasRows 为 false 吗?

感谢阅读。

【问题讨论】:

  • 当您直接使用 SQL Studio 运行查询时会发生什么?我敢打赌它会返回一行。
  • 似乎有些不对劲。构造查询是从sqlDataReader 获取 ID,所以我假设 ID 存在,因此您有行吗? FieldCount 返回列数,因为查询只有一列 FK_BarId 你总是得到 1。

标签: c# mysql asp.net mysqldatareader


【解决方案1】:

我更喜欢使用辅助 DataTabe 而不是 DataReader,如下所示:

DataTable dt = new DataTable();
dt.Load(commandList.ExecuteReader());

if(dt.Rows.Count > 0){

    //rows exists
}else{

    //no rows
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多