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