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

问题描述 投票:0回答:1

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

A = 0 B = 0 """从 TABLE 中选择 *,其中 (TABLE.FIELD = ? OR A = 0) AND (TABLE.FIELD = ? OR B = 0) ..... """

${A} == 0 且 ${B} == 0

python sqlite
1个回答
1
投票

在 Python 的 SQLite 中,您可以通过使用

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

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()

根据您的具体用例,将

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

© www.soinside.com 2019 - 2024. All rights reserved.