码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2017-09-07 00:59:38      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:split()   exec   .exe   set   中文字符   手动   man   中文   with   

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)"""

cursor.executemany(sql,list)
db.commit()

db.close()

注意事项:

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

 

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

标签:split()   exec   .exe   set   中文字符   手动   man   中文   with   

原文地址:http://www.cnblogs.com/TIMHY/p/7487651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!