gpt4 book ai didi

python - 将参数(列表或数组)传递给 in operator - python, sql

转载 作者:太空狗 更新时间:2023-10-30 02:19:43 26 4
gpt4 key购买 nike

<分区>

我有一个 python 列表。

article_ids = [1,2,3,4,5,6]

我需要像这样在 sql 语句中使用这个列表:

SELECT id FROM table WHERE article_id IN (article_ids)

如何将此列表提供给我的 IN() 子句?

我已经尝试了一些我用谷歌搜索的方法,但我无法弄清楚。

>> print ids_list
placeholders= ', '.join('?'*len(ids_list)) # "?, ?, ?, ... ?"
query = 'SELECT article_id FROM article_author_institution WHERE institution_id IN ({})'.format(placeholders)
print query
cursor.execute(query, ids_list)

我得到的错误信息:

SELECT article_id FROM article_author_institution WHERE institution_id IN (?)
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

例如:

ids_list = [9,10]

placeholders= ', '.join('%'*len(ids_list)) # "?, ?, ?, ... ?"
query = 'SELECT aid FROM article_author_institution WHERE instid IN ({})'.format(placeholders)
print query
cursor.execute(query, ids_list)

输出和错误信息是:

SELECT aid FROM article_author_institution WHERE instid IN (%, %)
Traceback (most recent call last):
File "deneme3.py", line 11, in <module>
cursor.execute(query, ids_list)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute
query = query % db.literal(args)
ValueError: unsupported format character ',' (0x2c) at index 61

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com