无法用python将List类型解析为mysql。

问题描述 投票:0回答:1

我试图从那些有列表或元组的记录中插入数据,我已经尝试用以下代码。

代码: 当我试图执行这个代码时,我得到了以下错误:

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,emails,ranksheld) VALUES (%s, %s, %s) "

    #Create list (array) of records
    records_list = [('Tim',['[email protected]', '[email protected]'],[2,3]), ('Mary',['[email protected]'],[40, 45, 52]), ('Sam',['[email protected]'],None), ('Fred',['[email protected]'],[4]) ]

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

    #Commit the connection to make the change on the database
    connection.commit()

当我试着执行这个代码时,我得到了以下错误。

InterfaceError: Failed executing the operation; Python type list cannot be converted

谁能帮帮我?

python mysql list tuples
1个回答
0
投票

问题是,你在tuples中有数组。如果你想插入多行相同的nameemail,你必须在你的数组中添加额外的元组。例子:

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,emails,ranksheld) VALUES (%s, %s, %s) "

    #Create list (array) of records
    records_list = [('Tim','[email protected]',2), ('Tim', '[email protected]',3), ('Mary','[email protected]',40), ('Mary','[email protected]', 45), ('Mary','[email protected]', 52), ('Sam','[email protected]',None), ('Fred','[email protected]',4) ]

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

    #Commit the connection to make the change on the database
    connection.commit()
© www.soinside.com 2019 - 2024. All rights reserved.