我很难让 python 中的一些 sql 正确地通过 MySQLdb。是 pythons 字符串格式让我很生气。
我的 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语句中使用通配符?
最佳答案
这些查询似乎都容易受到 SQL 注入(inject)攻击。
试试这样的:
curs.execute("""SELECT tag.userId, count(user.id) as totalRows
FROM user
INNER JOIN tag ON user.id = tag.userId
WHERE user.username LIKE %s""", ('%' + query + '%',))
其中有两个参数被传递给 execute()
。
关于带有 SQL 通配符和 LIKE 的 Python 字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3134691/