Inserting BYTEA values
Sidney Cadot <sidney.cadot-xMbZfEG+6CxmR6Xm/[email protected]> Mon, 9 Mar 2009 18:08:48 +0100
| Newsgroups | gmane.comp.python.db.pypgsql.user |
|---|---|
| Message-ID | <[email protected]> |
Dear all,
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
encoding "UTF8"'.
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
solution.
Any help would be greatly appreciated.
Sidney
##############
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)
cursor.execute(query, params)
# Say goodbye
cursor.close()
connection.close()
##############
------------------------------------------------------------------------------
Open Source Business Conference (OSBC), March 24-25, 2009, San Francisco, CA
-OSBC tackles the biggest issue in open source: Open Sourcing the Enterprise
-Strategies to boost innovation and cut costs with open source participation
-Receive a $600 discount off the registration fee with the source code: SFAD
http://p.sf.net/sfu/XcvMzF8H