我将 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
.
关于python - 参数 ?不使用 python postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876204/