Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing bytea field into PostgreSQL database via psycopg2

I have a list of values as such:

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

I would like to insert these into a bytea field in my PostgreSQL database, using psycopg2, but I am unfamiliar with byte strings in python.

What is the best way to achieve this?

like image 459
6 revs, 4 users 74% Avatar asked Jun 21 '26 12:06

6 revs, 4 users 74%


1 Answers

I am not sure if this is the correct way, but the following appears to work:

    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 a side note, when fetching it back out of 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')

The string can then be split into pairs and cast to integers.

like image 129
6 revs, 4 users 74% Avatar answered Jun 23 '26 01:06

6 revs, 4 users 74%



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!