Ignacio Bustos
Ignacio Bustos

Reputation: 1504

Npgsql DataReader Invalid attempt to read when no data is present

Im geting angry with this, i cant find a solution because the error handler have a huge lack of information. I have a PostGreSQL Database and i am using the Npgsql.dll to conect, everything works by now as normal. Except for somethings like this:

I have a "test" table with 2 Columns (name, description) and 4 rows.

Im using "dr As NpgsqlDataReader" to execute a simple command

"SELECT * FROM test"

But with no reason it doesnt work at all, there are almost no extra info or help for this, it seems to be something related to npgsql.dll when i get the error.

dr = comando.ExecuteReader()

        dr.Read()
        Debug.Print("{0}", dr.Item(1)) //Works, give "description" value data 
        Debug.Print("{0}", dr.Item(0)) //Works, give "name" value data
        Debug.Print("{0}", dr.GetName(0)) //Works, give column name "name"
        Debug.Print("{0}", dr.GetString(0)) //Works, again, same "name" value data
        Debug.Print("{0}", dr.GetValue(0)) //Works, same "name" value data
        While dr.HasRows

            For i As Integer = 0 To (dr.FieldCount - 1) //in this case, this is (2-1)
                Debug.Print("{0}", dr.GetName(i)) //works, give column name "name"
                Debug.Print("{0}", dr.Item(i))  //FAILSSSS
                'MsgBox(String.Format("{0}: {1}", dr.GetName(i), dr.Item(i))) //FAILSS
            Next
            dr.Read()
        End While
        dr.Close()

After the FAIL i just get from error handler: "Invalid attempt to read when no data is present"

It would be so gratefull to have some extra opinions here to help. Thanks by advance.

Upvotes: 0

Views: 1792

Answers (1)

Ignacio Bustos
Ignacio Bustos

Reputation: 1504

I found the problem, it wasn't related directly to

Invalid attempt to read when no data is present

error.

While dr.HasRows is FORBIDDEN

Old documentation doesn't have an explicit explanation of this boolean procedure.

Something for example like explaining if true means that "dr" has rows IN GENERAL of the query, or AFTER the actual pointer position (in this case "dr.read()").

The correct is obviously (not for me): "in general", always TRUE or FALSE for the query command received.

Postgres answer this with a lack of data, far away from the problem and that confused me

Best use of this:

If dr.HasRows Then
   While dr.Read()
         For i As Integer = 0 To (dr.FieldCount - 1)
             Debug.Print("{0}", dr.GetName(i))
             Debug.Print("{0}", dr.GetString(i))
             MsgBox(String.Format("{0}: {1}", dr.GetName(i), dr.Item(i)))
         Next
   End While
   dr.Close()
End If

I have to say that i found similars answer to this in others questions here that helped me find my particular solution. Thx to all of them, or you, if you are one of them.

Upvotes: 3

Related Questions