How to fix "can't adapt error" when saving binary data using python psycopg2
I ran across this bug three times today in one of our projects. Putting the problem and solution online for future reference.
impost psycopg2
con = connect(...)
def save(long_blob):
cur = con.cursor()
long_data = struct.unpack('<L', long_blob)
cur.execute(开发者_如何学Python'insert into blob_records( blob_data ) values (%s)', [long_data])
This will fail with the error "can't adapt" from psycopg2.
The problem is struct.unpack returns a tuple result, even if there is only one value to unpack. You need to make sure you grab the first item from the tuple, even if there is only one item. Otherwise psycopg2 sql argument parsing will fail trying to convert the tuple to a string giving the "can't adapt" error message.
impost psycopg2
con = connect(...)
def save(long_blob):
cur = con.cursor()
long_data = struct.unpack('<L', long_blob)
# grab the first result of the tuple
long_data = long_data[0]
cur.execute('insert into blob_records( blob_data ) values (%s)', [long_data])
"Can't adapt" is raised when psycopg doesn't know the type of your long_blob
variable. What type is it?
You can easily register an adapter to tell psycopg how to convert the value for the database.
Because it is a numerical value, chances are that the AsIs adapter would already work for you.
精彩评论