使用 Python 插入多个 MySQL 记录。错误:“Python‘元组’无法转换为 MySQL 类型”

Jav*_*Mon 3 python mysql

使用Python插入多个MySQL记录错误:Python“元组”无法转换为MySQL类型

错误代码:

Traceback (most recent call last):
  File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\conversion.py", line 181, in to_mysql
    return getattr(self, "_{0}_to_mysql".format(type_name))(value)
AttributeError: 'MySQLConverter' object has no attribute '_tuple_to_mysql'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 432, in _process_params
    res = [to_mysql(i) for i in res]
  File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 432, in <listcomp>
    res = [to_mysql(i) for i in res]
  File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\conversion.py", line 184, in to_mysql
    "MySQL type".format(type_name))
TypeError: Python 'tuple' cannot be converted to a MySQL type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "python_mysql_2.py", line 22, in <module>
    my_cursor.execute(mike_placeholders,records_list)
  File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 557, in execute
    psub = _ParamSubstitutor(self._process_params(params))
  File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 437, in _process_params
    "Failed processing format-parameters; %s" % err)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type
Run Code Online (Sandbox Code Playgroud)

Python代码:

#import sql.connector
import mysql.connector

#Create connection, added db we created#
connection = mysql.connector.connect(
    host='localhost', 
    user='root', 
    password='123', 
    database='testdb_1'
    ) 

#Create cursor for the connection
my_cursor = connection.cursor()

#Create SQL statement with placeholders and put in variable 
mike_placeholders="INSERT INTO users (name,email,age) VALUES (%s, %s, %s) "

#Create list (array) of records
records_list = [('Tim','Tim@tim.com',32), ('Mary','Mary@mary.com',40), ('Sam','Sam@sam.com',50), ('Fred','Fred@fred.com',22) ]

#Execute cursor, requires SQl statement variable, record variable
my_cursor.execute(mike_placeholders,records_list)

#Commit the connection to make the change on the database
connection.commit()
Run Code Online (Sandbox Code Playgroud)

Jav*_*Mon 9

啊啊,我用错了 Python 术语。

我应该在executemany使用tuple.

my_cursor.executemany(mike_placeholders,records_list)
Run Code Online (Sandbox Code Playgroud)