I have problems inserting 'BYTEA'-type values using PgSQL.
The code fragment given below fails to do what I want; as is, it gives
me a 'libpq.OperationalError: ERROR: invalid byte sequence for
I've tried many variations: wrapping 'data' as a PgSQL.PgBytea
instance; using PgSQL.QuotePgBytea(); setting the encoding in the
PgSQL.connect() call ...
However, I have not succeeded in doing what the code below intends to
do: inserting a BYTEA field into the database comprising all 256
possible byte values in sequence.
What am I doing wrong? Should I not use the Python 'str' type for this
perhaps? I've checked the docs but I have been unable to find a
Any help would be greatly appreciated.
from pyPgSQL import PgSQL
# open the database; make a cursor
connection = PgSQL.connect(database="testdb")
cursor = connection.cursor()
# Suppose I have a 256-byte string like this,
# containing all 256 possible byte values:
data = str.join("", [chr(i) for i in range(0, 256)])
# And I want to insert this into a 'bintab' table
# that has a 'data' field of PostgreSQL type 'BYTEA':
query = "INSERT INTO bintab(data) VALUES (%s);"
params = (data, )
# Now execute this (THIS WILL THROW AN EXCEPTION)
# Say goodbye
On Mar 9, 2009, at 18:36, Clarence Gardner (ADECN) wrote:
> I don't know the details off the top of my head (it's been a couple
> of years), but I recall there's a Binary class somewhere (possibly
> in pypgsql, possible in a standard library) that you can wrap those
> things in.
Well, there's PgSQL.PgBytea, but I haven't been able to use to solve
my particular problem, unfortunately. I have a feeling it /should/
work, but it doesn't.
Sidney Cadot wrote:
> On Mar 9, 2009, at 18:36, Clarence Gardner (ADECN) wrote:
>> I don't know the details off the top of my head (it's been a couple
>> of years), but I recall there's a Binary class somewhere (possibly
>> in pypgsql, possible in a standard library) that you can wrap those
>> things in.
> Well, there's PgSQL.PgBytea, but I haven't been able to use to solve
> my particular problem, unfortunately. I have a feeling it /should/
> work, but it doesn't.
I'm storing compressed strings as binary data in PostgreSQL. For me
PgBytea(data) is working to convert the data into an argument suitable
I can't show the SQL code, as I'm using a wrapper, but I don't
remember doing anything special.
I'm using named parameters and a dictionary for the data.
The revisions are 2.5.1 for Python and pyPgSQL.