python - 在 postgresql 查询中使用 python 列表

标签 python postgresql

我的问题与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/

相关文章:

linux - 由于访问被拒绝,无法将 CSV 复制到数据库表

sql-server - 如何在 postgres 中使用具有唯一约束的聚类?

python - 这个lcm python代码我做错了什么?

python - Paramiko 获取排序的目录列表

sql - Postgres 使用主键索引作为覆盖索引

postgresql - 如何在 ON CONFLICT DO UPDATE SET X = OLD.X + EXCLUDED.X 中引用 OLD.X

postgresql - 多列中的 COUNT 个 NULL

python - 为什么我的 python while 循环不会停止?

python - for 循环训练中缺少一批?

python - 在 django 中发布后保留选中的复选框