如何从两个python嵌套列表或列表元组转换数据(即:usernames
和scores
)插入名为'testdatabase_1_1'
的数据库的两个表(users
和game
)中,因此一个表(users
)的第一列(id
)将是primary key
,另一个表(game
)的第一列(userID
)将是foreign key
我想用cursor.executemany
方法而不是cursor.lastrowid
方法执行代码。
import mysql.connector
db= mysql.connector.connect(host= 'localhost', user='root',password='',database='testdatabase_1_1')
mycursor=db.cursor()
Table1='CREATE TABLE users (id int AUTO_INCREMENT PRIMARY KEY , name VARCHAR(50), passwd VARCHAR (50))'
Table2='CREATE TABLE game (userID int PRIMARY KEY , foreign key (userID) REFERENCES users(id), game1 int default 0 , game2 int default 0)'
# mycursor.execute(Table1)
# mycursor.execute(Table2)
usernames=[('tim','techwithwim'),
('joei','joy123'),
('sara','sara1234')
]
scores=[(45,100),
(30,200),
(46,124)
]
mycursor.executemany('INSERT INTO users (name, passwd) values (%s,%s)' ,usernames)
mycursor.executemany('INSERT INTO game (userID, game1, game2) VALUES (%s, %s, %s)', scores)
db.commit()
当我想在executemany
方法中执行这些请求时,我得到了这个错误:
raise InterfaceError(f“执行操作失败;{err}”)from None mysql.connector.errors.InterfaceError:执行操作失败;SQL语句的参数不足
当我修改这部分代码时:
mycursor.executemany('INSERT INTO game (userID, game1, game2) VALUES (%s, %s, %s)', scores)
到
mycursor.executemany('INSERT INTO game (userID, game1, game2) VALUES (%s, %s, %s)', *scores)
它提出:
executemmany()接受3个位置参数,但给出了5个
注意,我知道使用for loop
方法和lastrowid
方法是可能的,没有任何错误,就像这样:
import mysql.connector
db= mysql.connector.connect(host= 'localhost', user='root',password='',database='testdatabase_1_1')
mycursor=db.cursor()
Table1='CREATE TABLE users (id int AUTO_INCREMENT PRIMARY KEY , name VARCHAR(50), passwd VARCHAR (50))'
Table2='CREATE TABLE game (userID int PRIMARY KEY , foreign key (userID) REFERENCES users(id), game1 int default 0 , game2 int default 0)'
# mycursor.execute(Table1)
# mycursor.execute(Table2)
usernames=[('tim','techwithwim'),
('joei','joy123'),
('sara','sara1234')
]
scores=[(45,100),
(30,200),
(46,124)
]
Q3= 'insert into users (name, passwd) values (%s,%s)'
Q4='insert into game(userID,game1,game2) values (%s,%s,%s)'
for x, user in enumerate(usernames):
mycursor.execute(Q3,user)
last_id= mycursor.lastrowid
mycursor.execute(Q4 ,(last_id,) + scores[x] )
db.commit()
1条答案
按热度按时间zkure5ic1#
的
https://chat.openai.com/chat
给了我这个答案