Salman Azmat
Salman Azmat

Reputation: 298

How to write null characters to a bytea column using psycopg2 in Python

I'm trying to write binary data into bytea column in PostgreSQL table. My data contains null characters and I get following error.

ValueError: A string literal cannot contain NUL (0x00) characters.

This is my code.

import numpy as np
fft = [0.0, 0.2, 0.0215]
[float(i) for i in fft]
blob = struct.pack('%sd' % np.size(fft), *fft)
cur.execute("""INSERT INTO fft (id, v) VALUES(%s, %s)""", ("widget_fft", blob))

id is of type text and v is of type bytea.

I have also tried using psycopg.Binary(blob), but it inserts backslashes which I don't want.

Upvotes: 1

Views: 2031

Answers (1)

Laurenz Albe
Laurenz Albe

Reputation: 247495

In Python 2.7, you have to use the psycopg2.Binary wrapper:

cur.execute("""INSERT INTO fft (id, v) VALUES(%s, %s)""",
            ("widget_fft", psycopg2.Binary(blob)))

See the documentation for details.

This is not required in Python 3.

I tried it and didn't see any backslashes. Can you show what exactly is in blob?

Upvotes: 1

Related Questions