skip to Main Content

I have data defined as double saved in a PSQL-Database (Actian) and I’m using DbDataReader to read the values. I know I can use GetDouble to read the value, but I would like read the raw value into a byte array. The GetBytes method comes back with InvalidCastException since it’s designed to be used with BLOB or VARBINARY. Is there any other way, like read the entire data buffer?

2

Answers


  1. Chosen as BEST ANSWER

    so I tested the code with SqlConnection, but unforunately the field that had the value -0 in DB came back with a 8 byte array with zeroes in MyDoubleArray. However, I tried to use basically the same code but in OleDB, which is operating on a lower level, and it worked fine. The last byte in MyDoubleArray contained a value of 128, indicating that the higest bit was set - just what I was looking for.

    using (OleDbCommand command = new OleDbCommand(sqlQuery, connection))
    {
        using (OleDbDataReader reader = command.ExecuteReader())
        {
            
            while (reader.Read())
            {
    
                 double d = (double)reader.GetDouble(0);
    
                byte[] MyDoubleArray = BitConverter.GetBytes(d); 
    
            }
         }
    }
    

    Now I can extract the value and find a way to save it a proper way :)


  2. Hum, a somewhat strange request.

    I can see wanting a int, a long, or bigint, or even a unsigned integer value being converted to a byte array. And even perhaps a packed decimal number, which in theory is a non floating point number.

    However, I am not all that sure it makes sense to convert a IEEE floating point number to a array of 8 bytes?

    I can’t think of any software system that will be happy to consume such a floating point value.

    However, using BitConverter should work.

    I don’t have the PostgreSQL provider installed, but using SQL server, this looks to work fine for me:

            string strSQL =
                @"SELECT HotelPrice FROM tblHotelsA WHERE ID = 10";
    
            DataTable dt = new DataTable();
    
            using (SqlConnection conn= new SqlConnection(Properties.Settings.Default.MyDB))
            {
                using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                {
                    conn.Open();
                    dt.Load(cmdSQL.ExecuteReader());
                }
            }
    
            double myDouble = (double)dt.Rows[0]["HotelPrice"];
    
            byte[] MyDoubleArray = BitConverter.GetBytes(myDouble);
    

    The result of above is a byte array of 8 bytes long.

    So, replace the SQL provider with the PostgreSQL provider, and the posted code should work fine for your needs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search