【发布时间】:2015-04-04 18:12:36
【问题描述】:
我正在尝试使用参数化查询通过 Python 脚本将数据插入 MySQL 数据库,而不是将参数格式化为字符串并将应用程序打开以进行 SQL 注入。
这是 Python 代码:
#!/usr/bin/python3
import MySQLdb as mdb
conn = mdb.connect("localhost", "fakeuser", "fakepassword", "testdb")
c = conn.cursor()
c.execute("INSERT INTO test VALUES (%s)", ("Test", ))
conn.commit()
conn.close()
当我运行脚本时,我得到以下堆栈跟踪:
Traceback (most recent call last):
File "./load.py", line 7, in <module>
c.execute("INSERT INTO test VALUES (%s)", ("Test", ))
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 184, in execute
self.errorhandler(self, exc, value)
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/connections.py", line 37, in defaulterrorhandler
raise errorvalue
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 171, in execute
r = self._query(query)
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 330, in _query
rowcount = self._do_query(q)
File "/opt/python3/lib/python3.2/site-packages/MySQL_python-1.2.3-py3.2-linux-x86_64.egg/MySQLdb/cursors.py", line 294, in _do_query
db.query(q)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1")
但是,我读过的所有文档都表明 %s 是正确的占位符。我尝试将%s 括在单引号中,但这会导致语句按字面意思插入该字符串,而不是替换给定的值,这是我所期望的。
以下是相关的软件版本:
- Python 3.2.3
- MySQL_python-1.2.3-py3.2
- MySQL 5.5.40-36.1
注意:我使用的是共享主机,无法升级软件。
【问题讨论】:
标签: python mysql mysql-python