Search code examples
c#oracle-databasedatareaderoledbdatareader

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


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;
        }

Solution

  • 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