如何创建带有列表作为参数的 SELECT 语句? [英] How do I create a SELECT statement with a list as a parameter?
问题描述
以下代码仅在列表targets_in_sw
中只有一个值时有效:
The following code only works when the list targets_in_sw
only has one value in it:
sw_current = cursor.execute("SELECT * from SOFTWARE_")
sw_current = sw_current.fetchall()
for sw_item in sw_current:
current_software_id = sw_item[0]
# Create Software XML Element
sw_element = ET.SubElement(root, "Software")
# Get all Targets for current sw_element
targets_in_sw = cursor.execute("SELECT TARGET2 from SOFTWARE_TARGET_ WHERE SOFTWARE1=?", (current_software_id,))
targets_in_software = targets_in_sw.fetchall()
targets_in_software = list(chain.from_iterable(targets_in_sw))
# Get all Target IDs for current sw_element
current_target_IDs = cursor.execute("SELECT * from TARGET_ WHERE id_=?", targets_in_software)
current_target_IDs = current_target_IDs.fetchall()
## The following line ONLY prints when my list contains one value ##
print current_target_IDs
问题
当 targets_in_software
是多个值的列表时,如何更改它以便我可以从 TARGET_
中选择所有内容?
Question
How can I change this so that I may select everything from TARGET_
when targets_in_software
is a list of multiple values?
注意事项:
如果您没有看到标签,我使用的是 SQLite3.
In case you didn't see the tags, I'm using SQLite3.
以下是循环过程中 targets_in_software
中的值的示例:
Here's an example of the values within targets_in_software
while going through the loop:
iteration targets_in_software
1 [21]
2 [28]
3 [29]
4 [91]
5 [92]
6 [94]
7 [217]
8 [218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228]
9 [251]
10 [261]
...etc.
推荐答案
您的原始 SQL 查询应如下所示:
Your raw SQL query should look like this:
SELECT val FROM table_name WHERE ref_val in ('val_one','val_two');
所以对于你的情况,你应该这样做:
So for your case, you should do:
targets_in_sw = cursor.execute("SELECT TARGET2 from SOFTWARE_TARGET_WHERE SOFTWARE1=(" + ",".join(targets_in_software) + ");")
请注意,这不会保护您免受 SQL 注入.
Please note that this will not protect you against SQL injection.
这篇关于如何创建带有列表作为参数的 SELECT 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!