Python mysql-表中数据的大量插入

2017-09-06 23:28:26

import pymysql

db = 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

 

posted @ 2017-09-06 23:32  hyserendipity  阅读(896)  评论(0编辑  收藏  举报