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

hgqdbh6s  于 11个月前  发布在  SQLite
关注(0)|答案(1)|浏览(196)

我使用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

5f0d552i

5f0d552i1#

在Python的SQLite中,可以通过使用execute()方法并将变量作为元组传递来使用WHERE子句中的变量。然而,您的查询似乎涉及直接字段比较和变量条件。为了实现这一点,您可能需要基于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_FIELDsome_other_value_for_FIELD替换为您所需的TABLE.FIELD字段值。此示例基于A和B的值动态构造查询,并使用参数来防止SQL注入漏洞。

相关问题