参数不适用于python postgres

我正在将python与postgres一起使用,我正在尝试这个简单的查询,但它不起作用,我无法找到原因

con = psycopg2.connect(**config)


self.cursor.execute("INSERT INTO mytable (id, age, year) VALUES (nextval('my_id_seq'), ?, ?)", ('77', '44'))

我收到此错误

psycopg2.ProgrammingError: syntax error at or near “,” LINE 1:
…year) VALUES (nextval(‘my_id_seq’), ?, ?)

编辑

这是错误

INSERT INTO mytable (id, age, year) VALUES (nextval('my_id_seq'), %s, %s)
'6.65', '4955/1'

  File "off.py", line 80, in writeRows
    self.cursor.execute(query, values)
TypeError: not all arguments converted during string formatting

码:

data = [('age', '6.65'), ('year', '4974/1'), . . ]
cols = ",".join(data.keys())
qmarks = ','.join(['%s' for s in data.keys()])
query = "INSERT INTO mytable (id, %s) VALUES (nextval('my_id_seq'), %s)" % (cols,qmarks)
self.cursor.execute(query, values)

解决方法:

psycopg2使用pyformat参数样式:

>>> import psycopg2
>>> psycopg2.paramstyle
'pyformat'

更换参数标记?与%s.

参见PEP 249 — Python Database API Specification v2.0 – paramstyle.

上一篇:枚举类型作为构造函数中的参数


下一篇:Java:数组大小的插入排序麻烦