SqlDataReader.HasRows即使结果为空也总是返回“ true”

时间:2019-03-28 10:15:19

标签: c# mysql asp.net mysqldatareader

浏览了关于SqlDataReader.HasRows的现象的多个主题之后,即使结果为空,该现象也始终返回true(尤其是当它涉及带有聚合的SQL查询时),我完全弄清了代码

但是我的示例非常简单,即使没有phpMyAdmin辅助行,HasRows也会返回TrueFieldCount会返回1

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为假吗?

感谢阅读。

1 个答案:

答案 0 :(得分:0)

我更喜欢使用辅助DataTabe代替DataReader,如下所示:

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

if(dt.Rows.Count > 0){

    //rows exists
}else{

    //no rows
}