How to read and insert bytea columns using psycopg2?

前端 未结 1 810
一整个雨季
一整个雨季 2021-01-18 03:31

I am working on a Python script to replicate some Postgresql tables from one environment to another (which does a little more than pg_dump

相关标签:
1条回答
  • 2021-01-18 04:03

    If you have this database structure:

    CREATE TABLE test (a bytea,
                       b int,
                       c text)
    

    then inserting binary data into the request can be done like so, without any wrappers:

    bin_data = b'bytes object'
    db = psycopg2.connect(*args)  # DB-API 2.0
    c = db.cursor()
    c.execute('''INSERT INTO test VALUES (%s, %s, %s)''', (bin_data, 1337, 'foo'))
    c.execute('''UPDATE test SET a = %s''', (bin_data + b'1',))
    

    Then, when you query it:

    c.execute('''SELECT a FROM test''')
    

    You'll receive a memoryview, which is easily converted back to bytes:

    mview = c.fetchone()
    new_bin_data = bytes(mview)
    print(new_bin_data)
    

    Output: b'bytes object1'

    Also, I'd suggest you not to assemble queries by string formatting. psycopg2's built-in parameter substitution is much more convenient and you don't have to worry about validating data to protect from SQL injections.

    0 讨论(0)
提交回复
热议问题