如何使用列表作为参数创建SELECT语句?

时间:2015-03-05 19:06:57

标签: python sqlite python-2.6

代码

当列表targets_in_sw中只有一个值时,以下代码有效:

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

问题

我如何更改此权限,以便TARGET_targets_in_software是多个值列表时从targets_in_software中选择所有内容?

备注:

如果您没有看到标签,我正在使用 SQLite3

以下是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. 在循环过程中的值的示例:

{{1}}

4 个答案:

答案 0 :(得分:2)

您的原始SQL查询应如下所示:

SELECT val FROM table_name WHERE ref_val in ('val_one','val_two');

因此,对于您的情况,您应该这样做:

targets_in_sw = cursor.execute("SELECT TARGET2 from SOFTWARE_TARGET_ WHERE SOFTWARE1=(" + ",".join(targets_in_software) + ");")

请注意,这不会保护您免受SQL注入。

答案 1 :(得分:1)

您可以使用in

以这种方式创建查询
SELECT * from TARGET_ WHERE id in tuple(targets_in_software)

targets_in_software有多个值时,这将有效。

答案 2 :(得分:1)

您需要在您的ORM中使用SQL IN operator。我没有足够的细节知道你在使用什么。以sw_item为参数,而不是current_software_id,尝试使用SELECT TARGET2 from SOFTWARE_TARGET_ WHERE SOFTWARE1 IN ?SELECT TARGET2 from SOFTWARE_TARGET_ WHERE SOFTWARE1 IN ?

答案 3 :(得分:1)

如果将元组作为execute的第二个参数传递,它将尝试将元组的每个元素替换为查询字符串中的占位符,例如:

stmt = "INSERT INTO mytable (name, id, rank) VALUES (%s, %s, %s)"
cursor.execute(stmt, (a, b, c))

创建一个查询,其中每个%s都被元组的元素替换。在您的情况下,您希望最终得到一个查询,其中整个元组在一个地方,因此您需要将其转换为字符串:

stmt = "SELECT * from TARGET_ WHERE id_ IN %s"
#convert list of ints to tuple of strings
stmt_param = str(tuple(map(str, targets_in_software)))
cursor.execute(stmt, stmt_param)

我认为这应该有用,虽然我无法测试它,因为我没有数据库可以测试。我希望这会有所帮助。