postgresql psycopg2“类型错误:并非所有参数都在字符串格式化期间转换”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/793679/
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
psycopg2 "TypeError: not all arguments converted during string formatting"
提问by Ian
I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error:
我正在尝试将二进制数据(漩涡散列)插入 PG 表中,但出现错误:
TypeError: not all arguments converted during string formatting
code:
代码:
cur.execute("""
INSERT INTO
sessions
(identity_hash, posted_on)
VALUES
(%s, NOW())
""", identity_hash)
I tried adding conn.Binary("identity_hash") to the variable before insertion, but get the same error.
我尝试在插入之前将 conn.Binary("identity_hash") 添加到变量中,但得到相同的错误。
The identity_hash column is a bytea.
identity_hash 列是一个字节。
Any ideas?
有任何想法吗?
采纳答案by Milen A. Radev
Have you taken a look at the "examples/binary.py" script in the psycopg2 source distribution? It works fine here. It looks a bit different than your excerpt:
您是否查看了 psycopg2 源代码分发中的“examples/binary.py”脚本?它在这里工作正常。它看起来与您的摘录有点不同:
data1 = {'id':1, 'name':'somehackers.jpg',
'img':psycopg2.Binary(open('somehackers.jpg').read())}
curs.execute("""INSERT INTO test_binary
VALUES (%(id)s, %(name)s, %(img)s)""", data1)
回答by piro
The problem you have is that you are passing the object as second parameter: the second parameters should be either a tuple or a dict. There is no shortcut as in the % string operator.
您遇到的问题是您将对象作为第二个参数传递:第二个参数应该是元组或字典。没有像 % 字符串运算符那样的快捷方式。
You should do:
你应该做:
cur.execute("""
INSERT INTO
sessions
(identity_hash, posted_on)
VALUES
(%s, NOW())
""", (identity_hash,))
回答by Salvador Dali
Encountered the same problem and found that this is actually covered in their FAQ
遇到了同样的问题,发现这个其实在他们的FAQ里有介绍
I try to execute a query but it fails with the error not all arguments converted during string formatting (or object does not support indexing). Why? Psycopg always require positional arguments to be passed as a sequence, even when the query takes a single parameter. And remember that to make a single item tuple in Python you need a comma! See Passing parameters to SQL queries.
我尝试执行一个查询,但它失败了,错误不是所有在字符串格式化期间转换的参数(或对象不支持索引)。为什么?Psycopg 始终要求将位置参数作为序列传递,即使查询采用单个参数也是如此。请记住,要在 Python 中创建单项元组,您需要一个逗号!请参阅将参数传递给 SQL 查询。
cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG
cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG
cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct
cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct