我很難在python中獲得一些sql來正確地通過MySQLdb。這是pythons字符串格式,這是殺了我。帶有SQL通配符和喜歡的Python字符串格式
我的sql語句使用LIKE關鍵字和通配符。我在Python中嘗試了許多不同的東西。問題是一旦我得到其中一個工作,MySQLdb中有一行代碼以字符串格式進行打包。
嘗試1:
"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '%%s%'" % (query)
這是一個沒有去。我得到的值錯誤:
ValueError: unsupported format character ''' (0x27) at index 128
嘗試2:
"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '\%%s\%'" % (query)
我從嘗試1.
嘗試3相同的結果:
like = "LIKE '%" + str(query) + "%'" totalq = "SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username " + like
這正確創建totalq變量,但現在當我去運行查詢時,我從MySQLdb中收到錯誤:
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py", line 158, in execute query = query % db.literal(args) TypeError: not enough arguments for format string
嘗試4:
like = "LIKE '\%" + str(query) + "\%'" totalq = "SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username " + like
這是企圖3.
輸出相同的這一切似乎真的很奇怪。如何在python中使用sql語句中的通配符?
要echo @bernie below:From psycopg docs:http://initd.org/psycopg/docs/usage.html#the-problem-with-the-query-parameters:「絕不,永遠不要使用Python字符串連接(+)或字符串參數插值(%)將變量傳遞給SQL查詢字符串。 「除了SQL注入攻擊之外,第二個好處是驅動程序」可以自動將Python對象與SQL文字進行轉換:使用此功能,您的代碼將更加健壯和可靠「。這與」天真處理查詢字符串的組成,例如使用字符串連接「 – 2013-06-10 13:21:09