Python mysql-表中数据的大量插入
发布日期:2022-04-02 18:15:39 浏览次数:6 分类:博客文章

本文共 627 字,大约阅读时间需要 2 分钟。

2017-09-06 23:28:26

import pymysqldb = pymysql.connect("localhost","root","hy1102","TESTDB",charset='utf8')cursor = db.cursor()list=[]with open("E:\\ee.txt","r") as f:    for line in f:        ls = line.split()        for i in range(0,len(ls)):            if ls[i] == "NULL":                ls[i] = None        list.append(ls)    f.close()sql ="""insert into shohin VALUES (%s,%s,%s,%s,%s,%s)"""try:  cursor.executemany(sql,list)  db.commit() except:   db.rollback()db.close()

注意事项:

  • charset='utf8' : 在有中文字符时必须写上
  • 使用excutemany(sql,list),可以一次处理大量的数据,且效率颇高。文件中的NULL目前采用的方式是手动替换成None
  • list中的数据可以是list也可以是tuple
  • excutemany中sql的替换符必须是%s

 

转载地址:https://www.cnblogs.com/hyserendipity/p/7487651.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Python mysql-表的创建,删除和更新
下一篇:Python mysql-常用对象

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年03月30日 03时15分17秒