尝试使用mysql python连接器执行预准备语句时,我得到NotImplementedError

时间:2018-05-25 18:45:39

标签: python mysql mysql-connector-python

我想使用预处理语句使用python将数据插入MySQL DB(版本5.7),但我一直得到一个NotImplementedError。 我在这里关注文档:https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html

使用mysql-connector-python库的Python 2.7和8.0.11版:

pip show mysql-connector-python
---
Metadata-Version: 2.1
Name: mysql-connector-python
Version: 8.0.11
Summary: MySQL driver written in Python
Home-page: http://dev.mysql.com/doc/connector-python/en/index.html

这是我正在运行的python脚本的已清理版本(没有特定的主机名,用户名,密码,列或表):

import mysql.connector
from mysql.connector.cursor import MySQLCursorPrepared

connection = mysql.connector.connect(user=username, password=password,
                                      host='sql_server_host',
                                      database='dbname')
print('Connected! getting cursor')
cursor = connection.cursor(cursor_class=MySQLCursorPrepared)
select = "SELECT * FROM table_name WHERE column1 = ?"
param = 'param1'
print('Executing statement')
cursor.execute(select, (param,))
rows = cursor.fetchall()
for row in rows:
    value = row.column1
print('value: '+ value)

我运行时遇到此错误:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    cursor.execute(select, (param,))
  File "/home/user/.local/lib/python2.7/site-packages/mysql/connector/cursor.py", line 1186, in execute
    self._prepared = self._connection.cmd_stmt_prepare(operation)
  File "/home/user/.local/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 969, in cmd_stmt_prepare
    raise NotImplementedError
NotImplementedError

1 个答案:

答案 0 :(得分:4)

CEXT将是enabled by default if you have itprepared statements are not supported in CEXT at the time of writing

您可以通过添加关键字参数use_pure=True来禁用连接CEXT,如下所示:

connection = mysql.connector.connect(user=username, password=password,
                                     host='sql_server_host',
                                     database='dbname',
                                     use_pure=True)