Morten Goodwin Olsen <go*****@realgoodwin.com> wrote:
...
I am having a bit of trouble inserting images into a postgres database
using python. The images should be stored in a bytea field.
I have tried both with an odbc connection and psycopg.
... I would be glad if someone new how to get around this problem.
You need to escape the binary data with psycopg.Binary. The full recipe
is in the Python Cookbook (1st edition, but I think I'll keep it for the
2nd edition as well), but basically it goes down to:
cursor.execute("CREATE TABLE justatest (name TEXT, ablob BYTEA)")
...
sql = "INSERT INTO justatest VALUES(%s, %s)"
for name in names:
cursor.execute(sql, (name, psycopg.Binary(data[name])) )
BTW, from somewhere on O'Reilly's site I believe you can download, for
free, a zipfile with all the code from the (printed, 1st edition) Python
Cookbook; doing that, unpacking the file, and grepping for BYTEA would
have gotten you the solution (although it's clearly nicer to read the
discussion too, and by buying the book you're also contributing
something to the Python Software Foundation, but, that _is_ by the
by;-).
Alex