2012-08-22 51 views
2

我試圖執行一個mysql查詢,它需要包含%字符......在構建查詢時,我遇到了一個python使用%的問題,並試圖將它作爲變量保存:python,%和mysql語句

statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) 
self.cursor.execute(statmt) 

這與自然barfs:

statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) 
TypeError: not enough arguments for format string 

我應該如何解決這個問題所以Python停止閱讀這是一個變量,它需要作爲字符串的一部分?

謝謝!

回答

7

當需要一個Python格式表達式內的字面%,使用%%

statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl) 

參見文檔section 5.6.2. String Formatting Operations獲得更多信息。

+0

非常好!謝謝! – Cmag

+0

現在,如果blah需要成爲「... ie .... SELECT tbl WHERE'email' LIKE%」% – Cmag

+1

要在Python雙引號字符串內轉義字面值''',請使用'\ 「'。或者,你可以使用三重引號的字符串,''「」你可以在其中「容易」引用「」。 –

2

您不需要使用字符串插值。 execute方法處理它給你,這樣你就可以做到這一點,而不是:

statmt="select id from %s WHERE `email` LIKE %blah%" 
self.cursor.execute(statmt, tbl) 
+0

這是一張表,而不是一個字符串,所以這實際上並不工作。 –

1

您可以使用str.format

statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl) 

確保你沒有創建一個SQL注入漏洞。

2

你應該%%

逃避你百分號你應該用戶參數化查詢,雖與?,而不是串插。