I can not read the values returned from the database using OracleDataReader

3

I'm having trouble reading the returned values from a select , on the line where I do:

OracleDataReader reader = cmd.ExecuteReader();

In read it brings me the values correctly, but on the next line where I do reader.Read() says that the enumeration did not produce results.

How do I solve this problem?

Source

OracleConnection cnn = new OracleConnection(DataFunctions.GetDefaultConnectionString()); OracleCommand cmd = cnn.CreateCommand(); OracleDataAdapter adapter = new OracleDataAdapter();
try
{
    cnn.Open();
    cmd.Connection = cnn;
    cmd.CommandText = String.Format("select * from VI_TESTE where cd_codigo = {0}", code);
    OracleDataReader reader = cmd.ExecuteReader();

    // Ao debugar, aqui tem registros

    if (reader.Read())
    {
        // aqui não tem mais registros
        var test1 = reader.GetValue(0);
    }
}
finally
{
    cnn.Close();
}
    
asked by anonymous 14.05.2015 / 18:29

2 answers

0

The OracleDataReader approach will possibly bring you problems in inspection. For your case, use only OracleDataAdapter as shown below:

using (var cnn = new OracleConnection(DataFunctions.GetDefaultConnectionString())) 
{
    var cmd = cnn.CreateCommand(); 

    try
    {
        cnn.Open();
        cmd.Connection = cnn;
        cmd.CommandText = String.Format("select * from VI_TESTE where cd_codigo = {0}", code);
        var ds = new DataSet();
        var adapter = new OracleDataAdapter(cmd);
        adapter.Fill(ds);

        // Inspecione aqui ds
    }
    finally
    {
        cnn.Close();
    }
}
    
14.05.2015 / 21:48
0

Try using the GetString method instead of GetValue.

The Read command checks to see if there is one more line, then it advances to the next line and returns true. According to the msdn documentation a>, the dataReader always starts before the first line of data, so you can run READ before you start reading (just like you did). The GetValue method, as per the documentation for the msdn returns the object in its native format. Maybe the field is null or it is not able to do the conversion, and so it gives error.

    
14.05.2015 / 21:01