1

After browsing a multitude topics on the phenomenon of SqlDataReader.HasRows which always returns true even with empty result (and especially when it is about an SQL query with an aggregate), I dry completely on my code

However my example is very simple and HasRows returns True, FieldCount returns 1 even when there is no phpMyAdmin side line.

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();

Do you know how to get HasRows false when there is no rows like in phpMyAdmin result?

Thanks for reading.

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
aurepito
  • 101
  • 11
  • What happens when you run your query directly with SQL studio? I'll bet it returns a single row. – Koby Douek Mar 28 '19 at 10:17
  • Something seems to be amiss. The query is constructed getting an ID from a `sqlDataReader`, so I assume the ID exists and you therefore have rows? `FieldCount` returns the number of columns and since the query has one column `FK_BarId` you'd always get 1. – J.R. Mar 28 '19 at 10:29

1 Answers1

1

I prefer to use an auxiliar DataTabe instead DataReader, something like this:

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

if(dt.Rows.Count > 0){

    //rows exists
}else{

    //no rows
}