在 postgresql 查询中使用 python list

ram*_*esh 3 python postgresql

我的问题与此非常相似,但我的列表中有字符串而不是整数。

我的python list

list = ['a', 'b'] #number of items varies from 1 to 6
Run Code Online (Sandbox Code Playgroud)

我想在 Postgres 查询中使用这个列表,如下所示

select * from sample where sub in ('a', 'b');
Run Code Online (Sandbox Code Playgroud)

我可以使用tuple(list)get ('a', 'b'),当我的列表长度变成一时,这没有用。我正在努力寻找一种方法来转换

['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)'
Run Code Online (Sandbox Code Playgroud)

但 postgres 预计

select * from sample where sub in ('a', 'b');
Run Code Online (Sandbox Code Playgroud)

Pau*_*tte 5

使用 psycopg2,它会为您正确处理您尚未想到的各种边缘情况。对于您的具体问题,请参阅http://initd.org/psycopg/docs/usage.html#adapt-tuple