Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 792
Dazzmaster1 Avatar asked Dec 24 '11 02:12

Dazzmaster1


1 Answers

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())
like image 68
Adam Rackis Avatar answered Nov 09 '22 06:11

Adam Rackis