天天看點

Python中SQL——LIKE中的%

需求:

做項目的過程中,使用了mysql資料庫,背景使用python來做邏輯層。項目中需要實作一個功能,通過輸入搜尋框中的字元去mysql中找到比對的文章的标題。

sql語句:select * from t_article where title like '%searchstr%'

報錯:

但是在python中%是一個格式化字元,是以如果需要使用%則需要寫成%%。從網上查了一些文章,大多數人的回答是:

cur.execute("select* from  t_article where title like '%%%s%%'" %  searchstr) 或者

cur.execute("select* from  t_article where title like %s" %  ('%%%s%%' % searchstr))

這樣print出sql語句之後為:

select * from t_article where title like '%生活%'

并且會報錯  typeerror: not enough arguments for format string

這個錯誤很明顯是提示格式化的時候出現了問題。

解決:

最終将在python中執行的sql語句改為:

sql = "select * from t_article where title like '%%%%%s%%%%'" % searchstr

執行成功,print出sql語句之後為:

select * from t_article where title like '%%生活%%'

原因:

python在執行sql語句的時候,同樣也會有%格式化的問題,仍然需要使用%%來代替%。是以要保證在執行sql語句的時候格式化正确。而不隻是在sql語句(字元串)的時候正确。