我很难在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