首页 > 解决方案 > Executemany 因“执行操作失败;无法处理参数”而失败

问题描述

我正在尝试使用 调整INSERT INTO我的 python 代码的性能cursor.executemany(),但我收到了一些错误。
编码:

import mysql.connector

mydb = mysql.connector.connect(
    host="database1",
    user="username1",
    passwd="password1",
    database="dbname"
)

data = [
  'A',
  'B',
  'C',
]

mycursor = mydb.cursor()
query = "INSERT INTO table_name (name) VALUES (%s)"
mycursor.executemany(query, data)
mydb.commit()

根据示例,这应该可以工作,但是,我遇到了错误:

Traceback (most recent call last):
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 308, in _batch_insert
    prepared = self._cnx.prepare_for_mysql(params)
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 632, in prepare_for_mysql
    raise ValueError("Could not process parameters")
ValueError: Could not process parameters

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "dbtest.py", line 18, in <module>
    mycursor.executemany(query, data)
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 350, in executemany
    stmt = self._batch_insert(operation, seq_params)
  File "/Users/filipniko/PycharmProjects/scrape/darwin-scrape/venv/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 329, in _batch_insert
    "Failed executing the operation; %s" % err)

mysql.connector.errors.InterfaceError: Failed executing the operation; Could not process parameters

笔记:

表架构如下所示:

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   | UNI | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

我究竟做错了什么?

标签: pythonmysql

解决方案


我发现我使用了错误的依赖项,我应该使用mySQLdb而不是mysql.connector

import MySQLdb as my

mydb = my.connect(
    host="database1",
    user="username1",
    passwd="password1",
    database="dbname"
)

data = [
  'A',
  'B',
  'C',
]

mycursor = mydb.cursor()
query = "INSERT INTO table_name (name) VALUES (%s)"
mycursor.executemany(query, data)
mydb.commit()

https://thepythonguru.com/inserting-rows/


推荐阅读