[英]sqlite select query including a “VALUES” in the WHERE clause returns correctly with sqlite but not with python sqlite3
[英]How to select all values in case of default in drop-down menu in sqlite3 query where clause
我想根據QComboBoxes在QTableWidget中顯示數據。 在選擇所有性別或選擇所有年齡的情況下,我要在sqlite3查詢的列中應用全選
gender = "select all both male and female"
connection.execute("SELECT * FROM child where region=? and hospital=? and ageInMonths=? and gender=?", (region,hospital,ageInMonths,gender))
歡迎使用Stackoverflow。
盡管這有點乏味,但是解決此問題的最明智的方法是建立要應用的條件列表以及需要插入的另一個數據值。 類似於以下(未經測試的)代碼,其中我假設如果搜索中不需要這些變量,則將其設置為None
。
conditions = []
values = []
if region is not None:
conditions.append('region=?')
values.append(region)
# And similar logic for each other value ...
if gender is not None:
conditions.append('gender=?')
values.append(gender)
query = 'SELECT * FROM child'
if conditions:
query = query + ' WHERE ' + ' AND '.join(conditions)
connection.execute(query, values)
這樣,如果要包括一列的所有值,只需將條件設置為None
即可從條件中排除if。
您可以有條件地構建where子句和參數列表。
在下面,我假設在ageInMonths
上選擇“ ageInMonths
和“ gender
變量時,它們實際上包含值“全部”。 您可以將其更改為代碼中實際傳遞的任何值(如果有所不同)。
當涉及到實際查詢時,獲取字段的所有值的最佳方法是將其完全從查詢的where
子句中完全排除。
所以像這樣:
query_parameters = []
query_string = "SELECT * FROM child where region=? and hospital=?"
query_parameters.append(region)
query_parameters.append(hospital)
if ageInMonths != 'all':
query_string += " and ageInMonths=?"
query_parameters.append(ageInMonths)
if gender != 'all':
query_string += " and gender=?"
query_parameters.append(gender)
connection.execute(query_string, query_parameters)
基本上,在同一時間,我們正在測試和構建SQL語句的動態部分(在query_string
),我們也在動態定義的變量列表傳遞給查詢query_parameters
,這是一個list
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.