python傳參情況的模糊查詢mysql
阿新 • • 發佈:2018-12-15
先看這個查詢語句:SELECT * FROM company WHERE CompanynameChinese LIKE '%條件%'
這語句在mysqldb的模組中會導致被轉義。因為%在python中是轉義字元,需要兩個%%代替%,但是我嘗試這樣寫:
SELECT * FROM company WHERE CompanynameChinese LIKE '%%%%%s%%%%%'還是會報錯:
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '條件'%%'' at line 1")
下面是解決的辦法:
在python的mysqldb中,他已經會做一些字元的轉義. 比如你傳進一個字串,你不需用“ ”引起來,因為mysqldb會判斷你的字元是否是整形或者是字串,然後順手幫你轉義。
最終的正確語法是:
sql = """SELECT * FROM company WHERE CompanynameChinese LIKE %s"""
盡情的傳參吧!!!