Dazzmaster1
Dazzmaster1

Reputation: 169

Error: "No data exists for the row/column" using OdbcDataReader

Even though I know that there is data for the exact SQL query I'm performing, for the fact that I am doing the SQL query directly on the database, I continually get an exception saying that no data exists. My code is below:

      try
        {
            dbConnection.Open();

            // Process data here.
            OdbcCommand dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = "select forename from tblperson where personcode in (select clientcode from tblclient) and surname = '######'";
            OdbcDataReader dbReader = dbCommand.ExecuteReader();

            Console.WriteLine(dbReader.GetString(0));

            dbReader.Close();
            dbCommand.Dispose();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            dbConnection.Close();
        }

Can anyone give me reasons as to why this would be happening. The query should return a single result, and I'm currently only doing this to ensure that it is working, which it doesn't appear to be. Any help would be greatly appreciated.

Upvotes: 5

Views: 4546

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83358

After ExecuteReader is called, the reader is positioned before the first returned record. To read the first record you need to call Read()

dbReader.Read()

Or of course if there are multiple rows:

while (dbReader.Read())

Upvotes: 6

Related Questions