Python 字符串格式化与 SQL 通配符及 LIKE
我在用Python通过MySQLdb执行一些SQL语句时遇到了麻烦,主要是Python的字符串格式化让我很困惑。
我的SQL语句使用了LIKE关键字和通配符。我在Python中尝试了很多不同的方法,但每当我找到一个可行的方案时,MySQLdb中的某行代码又对字符串格式不满意。
第一次尝试:
"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
第二次尝试:
"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '\%%s\%'" % (query)
结果和第一次尝试一样。
第三次尝试:
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
第四次尝试:
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
这次的输出和第三次一样。
这一切看起来都很奇怪。我该如何在Python中使用SQL语句中的通配符呢?
8 个回答
在Python的字符串格式化中,如果你想要处理&符号,可以把&符号写两次:
'%%%s%%' % search_string
补充:不过我也非常赞同另一个回答。直接在SQL查询中替换字符串几乎总是个坏主意。
这些查询看起来都容易受到SQL注入攻击。
可以试试下面这种写法:
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()
方法。
这不是关于字符串格式的问题,而是关于如何根据数据库操作的要求在Python中执行查询的问题(PEP 249)。
可以尝试这样的做法:
sql = "SELECT column FROM table WHERE col1=%s AND col2=%s"
params = (col1_value, col2_value)
cursor.execute(sql, params)
这里有一些关于psycopg2的例子,里面有一些解释,这些解释对于mysql也适用(mysqldb同样遵循PEP249的数据库API指导2.0:这里是mysqldb的例子)。