如何在where子句中使用变量if条件?

How can I use a variable if condition inside the where clause?

提问人:Orxan Mirzəyev 提问时间:11/17/2023 最后编辑:John GordonOrxan Mirzəyev 更新时间:11/17/2023 访问量:46

问:

我使用 Python 和 SQLite 我想在字符串查询中使用局部变量条件。 我该怎么做,如下所示?

A = 0
B = 0
"""Select * from TABLE where (TABLE.FIELD = ? OR A = 0) AND (TABLE.FIELD = ? OR B = 0) ..... """

${A} == 0 和 ${B} == 0

蟒蛇 SQLite

评论

0赞 John Gordon 11/17/2023
你是在问如何动态设置,还是如何动态设置和?还是两者兼而有之?TABLE.FIELDAB

答:

5赞 ali 11/17/2023 #1

在 Python 的 SQLite 中,您可以通过使用该方法并将变量作为元组传递来在子句中使用变量。但是,您的查询似乎涉及直接字段比较和可变条件。为此,您可能需要根据 A 和 B 的值动态构造查询。WHEREexecute()

import sqlite3

# Assuming A and B are variables
A = 0
B = 0

# Your base query
base_query = "SELECT * FROM TABLE WHERE"

# Conditions based on A and B values
conditions = []
parameters = []

# Condition for TABLE.FIELD = ? or A = 0
if A == 0:
    conditions.append("(TABLE.FIELD = ? OR A = 0)")
    parameters.append(some_value_for_FIELD)  # Replace some_value_for_FIELD with your desired value
else:
    conditions.append("TABLE.FIELD = ?")
    parameters.append(some_other_value_for_FIELD)  # Replace some_other_value_for_FIELD with another value

# Condition for TABLE.FIELD = ? or B = 0
if B == 0:
    conditions.append("(TABLE.FIELD = ? OR B = 0)")
    parameters.append(some_value_for_FIELD)  # Replace some_value_for_FIELD with your desired value
else:
    conditions.append("TABLE.FIELD = ?")
    parameters.append(some_other_value_for_FIELD)  # Replace some_other_value_for_FIELD with another value

# Joining conditions
full_query = base_query + " AND ".join(conditions)

# Establish connection and execute query
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
cursor.execute(full_query, tuple(parameters))

# Fetch results
results = cursor.fetchall()

# Process results
for row in results:
    # Do something with each row
    print(row)

# Close the connection
conn.close()

根据您的特定用例,将 和 替换为所需的字段值。该示例根据A和B的值动态构造查询,并使用参数来防止SQL注入漏洞。some_value_for_FIELDsome_other_value_for_FIELDTABLE.FIELD

评论

0赞 Orxan Mirzəyev 11/17/2023
非常非常感谢:)这不是最简单的方法吗?