postgresql 使用python psycopg2保存二进制数据时如何解决“无法适应错误”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2149515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-20 00:00:18  来源:igfitidea点击:

How to fix "can't adapt error" when saving binary data using python psycopg2

pythonpostgresqlpsycopg2unpackiterable-unpacking

提问by Great Turtle

I ran across this bug three times today in one of our projects. Putting the problem and solution online for future reference.

我今天在我们的一个项目中遇到了这个错误 3 次。将问题和解决方案放到网上以备将来参考。

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 fail with the error "can't adapt" from psycopg2.

这将因来自 psycopg2 的错误“无法适应”而失败。

采纳答案by Great Turtle

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.

问题是 struct.unpack 返回一个元组结果,即使只有一个值要解包。您需要确保从元组中获取第一个项目,即使只有一个项目。否则 psycopg2 sql 参数解析将无法尝试将元组转换为字符串,并给出“无法适应”错误消息。

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])

回答by piro

"Can't adapt" is raised when psycopg doesn't know the type of your long_blobvariable. What type is it?

当 psycopg 不知道long_blob变量的类型时,会引发“无法适应” 。它是什么类型?

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

您可以轻松注册一个适配器来告诉 psycopg 如何转换数据库的值。

Because it is a numerical value, chances are that the AsIsadapter would already work for you.

因为它是一个数值,所以AsIs适配器可能已经适合您。