我有一个名为people2
的列表,如下所示:
['xloS4ooQOT',
'3s4LyNyHs3',
'NRL6zNePCT',
'7hkLogfk8T',
'5JcUkJ8FLO',
'LZ6DMUfnEA',
'CmBaomzMXC',
'M5OPb0yf09',
'CqG2XYGPxk']
我试图通过psycopg2
模块将其作为postgres查询的基础:
query = "SELECT userid, measurementvalue FROM db WHERE userid IN (%s)"
cur.execute(query, people2[1:5])
这会产生以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-5825c6e2c3fa> in <module>()
1 query = "SELECT userid, measurementvalue, displaydate, datatype FROM parse_dataobject WHERE userid IN (%s)"
----> 2 cur.execute(query, people2[1:5])
3 for r in rows[:5]:
4 print(r)
TypeError: not all arguments converted during string formatting
我也尝试删除括号,但这会导致相同的结果:
query = "SELECT userid, measurementvalue, displaydate, datatype FROM parse_dataobject WHERE userid IN %s"
我只是想跟随文档+之前的帖子(Python List to PostgreSQL Array),但我似乎错过了一些东西。我正在做什么有什么问题?
答案 0 :(得分:2)
来自Lists adaptation上的psycopg2文档,您的代码应如下所示:
query = "SELECT userid, measurementvalue FROM db WHERE userid = any(%s)"
cur.execute(query, (people2[1:5],))
答案 1 :(得分:0)
Python元组转换为psycopg2中的sql列表:
cur.mogrify("SELECT * FROM table WHERE column IN %s;", ((1,2,3),))
会输出
SELECT * FROM table WHERE column IN (1,2,3);
你需要转换元组中的列表并在使用此元组之后,例如:
people2 = ['xloS4ooQOT', '3s4LyNyHs3', 'NRL6zNePCT', '7hkLogfk8T', '5JcUkJ8FLO', 'LZ6DMUfnEA', 'CmBaomzMXC', 'M5OPb0yf09', 'CqG2XYGPxk']
query = "SELECT userid, measurementvalue FROM db WHERE userid IN %s"
cur.execute(query, tuple(people2[1:5]))