How to fix "unable to adapt error" error when saving binary data using python psycopg2

I met this error three times today in one of our projects. Entering a 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('insert into blob_records( blob_data ) values (%s)', [long_data]) 

This will result in an error if the error "cannot be adapted" from psycopg2.

+4
source share
2 answers

The problem is that struct.unpack returns the result of the tuple, even if there is only one value to unpack. You need to make sure that you take the first element from the tuple, even if there is only one element. Otherwise, parsing psycopg2 sql will not try to convert the tuple to a string giving a "cannot 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]) 
+4
source

"Unable to adapt" occurs when psycopg does not know the type of your variable long_blob . Which type?

You can easily register an adapter to tell psycopg how to convert the value for the database.

Since this is a numerical value, AsIs will most likely work.

+1
source

Source: https://habr.com/ru/post/1299579/


All Articles