Avatar of suhsalman
suhsalman
 asked on

Oracle Data Reader Has One Row But I Can NOT Retrieve it.

Here is a code snippets and debug result:

******************************************************************************

sql = "SELECT O.Latitude L, O.Longitude M, D.Latitude, D.Longitude";
            sql += "  FROM Locations O, Locations D";
            sql += " WHERE O.Town='" + OriginationComboBox.Text + "' AND";
            sql += " D.Town='" + DestinationComboBox.Text + "'";

            cmd = new OracleCommand(sql, con);
            dr = cmd.ExecuteReader();
            string x= dr[0];            //InvalidOperationException: No data exists for the row or column.
            string y=dr.GetString(1);      //InvalidOperationException No data exists for the row or column.
*********************************************************************************

Debug Result Using Immediate windows:

dr.HasRows
true

dr.HasRows
true

dr.Depth
0

dr.FieldCount
4

dr.GetName(0)
"L"

dr.Read()
true
dr.Read()
false
*****************************************************************************
The attached picture shows a quick watch for dr (OracleDataReader) state at run time exactly when the InvalidOperationException was thrown.
*****************************************************************************

If I excute the query utilizing SQLPlus IDE the result will be:

SQL> SELECT O.Latitude L, O.Longitude M, D.Latitude, D.Longitude
  2  FROM Locations O, Locations D
  3  WHERE O.Town='Amman' AND D.Town='Paris';

         L          M   LATITUDE  LONGITUDE
---------- ---------- ---------- ----------
     31.57      35.52       48.5        2.2

SQL>


Capture.JPG
Oracle DatabaseC#SQL

Avatar of undefined
Last Comment
Anurag Thakur

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
p_davis

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
suhsalman

ASKER
Yeah, It's wroking very well,
But why so ? why I sould used Read() ?
p_davis

for that, i don't have an answer other than its just the way that the datareader works.
Anurag Thakur

you are using datareader
data reader is a connected mode and does not bring data from the database in the connected mode till the time you do a read
so you have to use the read()

if (dr.HasRows)
{
    while (dr.Read())
    {
        //do operation here
     }
}

this is the reason you have to do a read
Your help has saved me hundreds of hours of internet surfing.
fblack61