尝试使用 mysql python 连接器执行准备好的语句时出现 NotImplementedError

I get NotImplementedError when trying to do a prepared statement with mysql python connector

我想使用准备好的语句将数据插入到使用 python 的 MySQL 数据库(版本 5.7)中,但我一直收到 NotImplementedError。 我正在关注这里的文档:https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html

使用 Python 2.7 和 mysql-connector-python 库的 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 脚本的清理版本(没有特定的主机名、用户名、密码、列或表)我正在 运行ning:

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

CEXT will be enabled by default if you have it, and prepared 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)

即将发布的 mysql-connector-python 8.0.17 版本(根据 MySQL bug report)将包含对 CEXT 中准备好的语句的支持。因此,一旦可用,升级到至少 8.0.17 即可解决此问题,而无需 use_pure=True.