OracleDataReader reader.Read() starts to read rows from the second record row, skipping the first row record

1.4k Views Asked by At

I have a SQL command and it returns 8 rows from the database.

When I use reader.Read() it starts at the second line, so I loose the fist row result. I don't know why it's skipping the first row record.

command.CommandText = "SELECT ATTRIBUTE_DESCRIPTION, SUBSTR(ATTRIBUTE_DATATYPE, 2, 6) FROM " + proj.PID_Schema + "PIDD.ATTRIBUTES@" + proj.PID_Database + " WHERE " +
                "attribute_name LIKE 'Controller' " +
                "OR attribute_name LIKE 'Initials' " +
                "OR attribute_name LIKE 'IOType' " +
                "OR attribute_name LIKE 'NetworkType' " +
                "OR attribute_name LIKE 'SignalOutput' " +
                "OR attribute_name LIKE 'SignalInput' " +
                "OR attribute_name LIKE 'SPIInstrumentType' " +
                "OR attribute_name LIKE 'Substation' ORDER BY 1";

            try
            {
                reader = command.ExecuteReader();
                reader.Read();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        codelistsNumbersDict.Add(reader.GetValue(0).ToString(), reader.GetValue(1).ToString());
                    }
                }
            }
            catch (Exception)
            {
            }

            connection.Close();

            return codelistsNumbersDict;
        }
2

There are 2 best solutions below

0
dani herrera On BEST ANSWER

Do you have two reads:

reader = command.ExecuteReader();
reader.Read(); // <--- FIRST READ (skipe first row)

if (reader.HasRows)
{
    while (reader.Read())  // <---- SECOND READ
    {

Because of this, you starting reading on second row.

If you take a look to Retrieve data using a DataReader sample, it only has one read:

SqlDataReader reader = command.ExecuteReader();
                   // <-- No read here on sample!
if (reader.HasRows)
{
    while (reader.Read()) // <-- Just ONE READ
    {

Doc screenshot:

screenshot with the full code available at https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader

0
RamblinWreckinVA On

As mentioned in @dani-herrera's answer, you are calling reader.Read() twice.

Also, you don't need the if (reader.HasRows), since if there are no rows the code inside the do loop won't execute. If you need to know the rows processed, you can always add a counter.

            try
            {
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    codelistsNumbersDict.Add(reader.GetValue(0).ToString(), reader.GetValue(1).ToString());
                }
            }