【发布时间】:2011-03-09 06:15:32
【问题描述】:
我很难让 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: 索引 128 处不支持的格式字符 ''' (0x27)
尝试 2:
"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '\%%s\%'" % (查询)
我从尝试 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 收到错误:
文件“build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py”,行 158、在执行query = query % db.literal(args) TypeError: not enough 格式字符串的参数
尝试 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语句中使用通配符?
【问题讨论】:
-
在下面回显@bernie:来自 psycopg 文档:initd.org/psycopg/docs/…:“永远,永远,永远不要使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串. 甚至在枪口下也没有。”除了 SQL 注入攻击之外,第二个好处是驱动程序“可以自动将 Python 对象与 SQL 文字转换:使用此功能,您的代码将更加健壮和可靠”。这与“组合查询字符串的简单方法,例如使用字符串连接。”
标签: python sql format sql-like