我的问题与this 非常相似但我的列表中有字符串而不是整数。
我的 python 列表
:
list = ['a', 'b'] #number of items varies from 1 to 6
我想像这样在 Postgres 查询中使用这个列表
select * from sample where sub in ('a', 'b');
我可以使用 tuple(list)
来获取 ('a', 'b')
,当我的列表长度变为 1 时,这没有用。我正在努力寻找一种转换方法
['a']
到 ('a')
['a', 'b']
到 ('a', 'b')
我试过了
In[91]: myquery = "select * from sample where sub in (%s)" % ",".join(map(str,list))
In[92]: myquery
Out[92]: 'select * from sample where sub in (a,b,c)'
但是 postgres 期望
select * from sample where sub in ('a', 'b');
最佳答案
使用 psycopg2,它会为您正确处理您尚未想到的各种边缘情况。对于您的具体问题,请参阅 http://initd.org/psycopg/docs/usage.html#adapt-tuple
关于python - 在 postgresql 查询中使用 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39460508/