Inserting multiple rows using executemany command in mysql

While creating a table in a database, a row marked as “AUTO_INCREMENT” is necessary for multiple inserting:

1
2
3
4
5
6
7
8
CREATE TABLE university (
id int(8) NOT NULL AUTO_INCREMENT,
#without AUTO_INCREMENT, there will be an error while inserting multiple rows
name varchar(50) NOT NULL,
university varchar(50) NOT NULL,
major varchar(50) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Then, create an array of the tuples you want to insert:

1
2
3
4
5
6
data = [("abc",'四川大学','口腔医学'),
("def",'北京师范大学','教育学类'),
("ghi",'北京工业大学','数学类'),
("jkl",'北京邮电大学','电子信息'),
("mno",'北京理工大学','未来精工技术'),
]

And use executemany command to insert:

1
2
3
4
5
6
7
8
9
try:
# 执行sql语句,插入多条数据
cursor.executemany("insert into university(name, university, major) values (%s, %s, %s)" , data)
# 提交数据
db.commit()
except:
# 发生错误时回滚
db.rollback()
print('error')

lines about connecting to database and ceating cursor instance is ignored

Inserting multiple rows using executemany command in mysql

http://gong208.github.io/2022/07/20/2022-07-21-mysql/

Author

Jiangshan Gong

Posted on

2022-07-20

Updated on

2023-08-11

Licensed under

Comments