参数?不使用python postgres

时间:2014-01-02 04:09:34

标签: python postgresql parameters

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

con = psycopg2.connect(**config)


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

我收到此错误

  
    

psycopg2.ProgrammingError:语法错误在“,”LINE 1处或附近:     ...年)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

CODE:

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)

1 个答案:

答案 0 :(得分:3)

psycopg2使用pyformat param样式:

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

将参数标记?替换为%s


请参阅PEP 249 -- Python Database API Specification v2.0 - paramstyle