本文主要是介绍20220427-day47:将csv文件的内容录入到MySQL数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import datetime
import pymysql
def insert_db(multi_row_list):
# 连接指定数据
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db="day25db")
cursor = conn.cursor()
# 单独增加数据
sql = 'insert into news(nid,title,url) values(%s,%s,%s);'
cursor.executemany(sql, multi_row_list)
conn.commit()
# 关闭数据库连接
cursor.close()
conn.close()
def run():
with open('data.csv', mode='rt', encoding='utf-8') as file_object:
# 批量在数据库中插入,每次最多插入10条
part_list = []
for line in file_object:
nid, others = line.strip().split(",", maxsplit=1)
title, url = others.rsplit(',', maxsplit=1)
part_list.append([nid, title, url])
if len(part_list) == 10:
insert_db(part_list)
part_list.clear()
if part_list:
insert_db(part_list)
if __name__ == '__main__':
run()
这篇关于20220427-day47:将csv文件的内容录入到MySQL数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!