带有 SQL 通配符和 LIKE 的 Python 字符串格式

标签 python sql format sql-like

我很难让 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/

相关文章:

python - 如何将中间总和列添加到 pandas 数据框中?

python - PyGTK 中简单、通用且可重复使用的输入对话框(有时称为输入对话框)

mysql - Node js不会在mysql表中插入主键

jquery - 带日期限制的屏蔽输入插件

perl - 如何使用 Perl 格式以科学记数法书写?

r - 使用 read.table 或 readLines 的条件输入

python - Django 嵌套内联 TemplateDoesNotExist

python - PHP 中 python3 的 function_exists

sql - sqlite 中与 MySQL 中的 find_in_set(value,set) 等效的函数是什么?

mysql - 使用 HeidiSQL 生成 sql