Importing a byte field into a PostgreSQL database via psycopg2

I have a list of values โ€‹โ€‹as such:

row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0']

I would like to insert them into a field byteain my PostgreSQL database using psycopg2, but I am not familiar with byte strings in python.

What is the best way to achieve this?

+3
source share
1 answer

I'm not sure if this is correct, but the following works:

    row = ['0x14', '0xb6', '0xa1', '0x0', '0xa1', '0x0']
    as_hex = ''.join(byte[2:].zfill(2) for byte in row)
  # as_hex = '14b6a100a100'
    bytes = buffer(as_hex.decode('hex'))

    cur.execute("INSERT INTO mylog (binaryfield) VALUES (%(bytes)s)", 
                {'bytes': bytes})

Just note that when retrieving it from the database, psycopg2 provides it as a buffer, the first 4 bytes of which are the total length, so get the original data as:

    cur.execute("SELECT binaryfield FROM mylog")
    res = cur.fetchone()
    my_data = str(res[4:]).encode('hex')

Then this line can be paired and applied to integers.

+2
source

Source: https://habr.com/ru/post/1735244/


All Articles