Python使用sql語句對mysql數(shù)據(jù)庫多條件模糊查詢的思路詳解
def find_worldByName(c_name,continent): print(c_name) print(continent) sql = " SELECT * FROM world WHERE 1=1 " if(c_name!=None): sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )" if(continent!=None): sql=sql+" AND ( continent LIKE '%"+continent+"%') " sql=sql+" AND dt=(SELECT dt FROM world order by dt desc limit 1) order by confirm desc " # "AND continent LIKE '%%%%%s%%%%'" \ # " order by dt desc " %(c_name,continent) # sql_temp = " SELECT * FROM world WHERE c_name LIKE '%"+c_name+"%' " res = query(sql) list= [] for i in res: # print(i) list.append(i) return list;
背景:
頁面的搜索框是有兩個搜索條件,一個是國家,一個是大洲。
那么在數(shù)據(jù)庫查詢的時候就會出現(xiàn)問題,如果國家傳的值是None那么使用AND連接的sql語句這個條件會被
整體判定為false,也就是另一個查詢條件 “大洲 ”就會作廢,為了防止參數(shù)出現(xiàn)這樣的錯誤。需要在寫sql語
句的時候對參數(shù)是否為空加一個判斷條件,然后逐層添加sql語句。
思路:
首先使用開頭的一個sql語句:
sql = " SELECT * FROM world WHERE 1=1 "
之后逐層判定參數(shù)是否為空,再拼接sql語句:
if(c_name!=None): sql=sql+"AND ( c_name LIKE '%"+c_name+"%' )" if(continent!=None): sql=sql+" AND ( continent LIKE '%"+continent+"%') " sql=sql+" AND dt=(SELECT dt FROM world order by dt desc limit 1) order by confirm desc "
還有一個地方需要注意:
sql語句傳參數(shù),參數(shù)是一個變量,有兩種方式:
① 直接拼接到sql語句中:
var c_name="test" sql_temp = " SELECT * FROM world WHERE c_name LIKE ' %"+c_name+"% '"
② 使用占位符%代替,在語句末尾再替換占位符:
sql = " SELECT * FROM world WHERE c_name LIKE '%%%%%s%%%%' AND continent LIKE '%%%%%s%%%%'" %(c_name,continent)
Tomorrow the birds will sing.
到此這篇關于Python使用sql語句對mysql數(shù)據(jù)庫多條件模糊查詢的思路詳解的文章就介紹到這了,更多相關Python mysql多條件模糊查詢內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Pytorch中的torch.nn.Linear()方法用法解讀
這篇文章主要介紹了Pytorch中的torch.nn.Linear()方法用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02