在Python 3中使用MySQLdb的参数化查询

时间:2015-04-04 18:12:36

标签: python mysql mysql-python

我正在尝试使用参数化查询通过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

注意:我使用的是共享主机,无法升级软件。

1 个答案:

答案 0 :(得分:0)

MySQL-Python项目不支持Python 3 - 请参阅the project web page,其中已提出“Python 3支持即将推出”,而the cheese shop entry仅提供Python 2.7版本和表示:

  

将来的版本将支持Python-3.0。

我听说过没有“-py3.2”发行版(或者可以通过搜索找到);您的主机可能有一些愚蠢的东西(例如this)以使库在Python 3上安装,但是能够安装库并不能保证它实际上能够正常工作。

这是an example of someone running into the same problem on a shared host

  

今天我在远程网络服务器上切换到Python v3.2.3   HostGator的。我在python v2.6.6上运行的cgi脚本现在可以生成   这些错误:

--> --> 
Traceback (most recent call last): 
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语法是正确的,你是对的;不幸的是,关于它的一些东西在Python 3中表现不佳。您可以尝试使用命名参数样式,看看是否能让您随处可见,但最好的办法是完全停止使用不受支持的库。例如,如果您的主持人也提供了an old version of Connector/Python