在linux2上的Python 2.7.10 [GCC 5.2.1 20151010]上执行此代码
import flask
from MySQLdb import escape_string as thwart
username="abc"
conn = MySQLdb.connect(host="localhost",user="root", passwd="xxxxxxx", db="pythonprogramming")
c = conn.cursor()
x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username)))
我收到以下错误:
Traceback (most recent call last):
File "", line 1, in TypeError: must be impossible, not str
这是我个人电脑上的MySQL版本
+-------------------------+------------------------------+
| Variable_name | Value
+-------------------------+------------------------------+
| innodb_version | 5.7.11
| protocol_version | 10
| slave_type_conversions |
| tls_version | TLSv1,TLSv1.1
| version | 5.7.11
| version_comment | MySQL Community Server (GPL) |
| version_compile_machine | x86_64
| version_compile_os | Linux
+-------------------------+------------------------------+
答案 0 :(得分:1)
下面的代码对我有效,查询变量x返回“1L”
`param1="john"
x = c.execute("""SELECT * FROM users WHERE username = %s """, (param1,))
`
虽然我不太明白为什么以下代码无效
param1="john"
x = c.execute("""SELECT * FROM users WHERE username = %s """ % (param1,))
和强>
param1="john"
x = c.execute("""SELECT * FROM users WHERE username = %s """ , (param1))
答案 1 :(得分:0)
您了解SQL注入的危险。这很好。
您甚至使用非常安全的execute
:参数化查询形式。以这种方式进行查询时,根本不需要转义。 execute
为你做了一切。因此解决方案是:
x = c.execute("SELECT * FROM users WHERE username = %
s",(用户名,))
如果你做了这样的事情(需要import
),你需要逃避:
x = c.execute("SELECT * FROM users WHERE username = %s" % escape_string(username))
如需进一步讨论,请查看Python MySQL Parameterized Queries