Search code examples
c#.netnpgsql

How to use NPGSQL.GetBytes() function


In my Postgres database, I have a bytea column. In my program, I can insert to this column, however, when I go to retrieve that data I get

System.InvalidOperationException: 'No row is available'

I can access the other column in that record but when I try either of these methods:

byte[] bytes = new byte[16];
bytes = (byte[])dr[3];


byte[] bytes = new byte[16];
dr.GetBytes(3, 0, bytes, 0, 16);

The error gets thrown. Thanks in advance.

EDIT: Added the query

string sql = "SELECT * FROM as_users WHERE name = @name";

        if (OpenConnection())
        {
            NpgsqlCommand npgsqlCommand = new NpgsqlCommand(sql, Connection);
            npgsqlCommand.Parameters.AddWithValue("name", username);
            npgsqlCommand.Prepare();
            NpgsqlDataReader dr = npgsqlCommand.ExecuteReader();

            if (dr.Read())
            {
                //Doesnt work
                byte[] bytes = new byte[16];
                dr.GetBytes(3, 0, bytes, 0, 16);

                //Does work
                string name = dr.GetString(1);
            }
        }

enter image description here


Solution

  • The issues explained were caused by an error within the database, not the NPGSQL function. Dropping and recreating the table solved the issue. Below is what I believe is an acceptable way to access data from a bytea column.

    byte[] bytes = new byte[16];
    dr.GetBytes(3, 0, bytes, 0, 16);