python文件读写并使用mysql批量插入示例分享(python操作mysql)

yipeiwu_com6年前Python基础

复制代码 代码如下:

# -*- coding: utf-8 -*-
'''
Created on 2013年12月9日

@author: hhdys
'''

import os
import mysql.connector

config = {
  'user': 'root',
  'password': '******',
  'host': '127.0.0.1',
  'database': 'test',
  'raise_on_warnings': True,
}
cnx = mysql.connector.connect(**config)

class ReadFile:
    def readLines(self):
        f = open("E:/data/2013-11-5.txt", "r", 1, "utf-8")
        i=0
        list=[]
        for line in f:
            strs = line.split("\t")
            if len(strs) != 5:
                continue
            data=(strs[0], strs[1], strs[2], strs[3], strs[4].replace("\n",""))
            list.append(data)
            cursor=cnx.cursor()
            sql = "insert into data_test(uid,log_date,fr,is_login,url)values(%s,%s,%s,%s,%s)"
            if i>5000:
                cursor.executemany(sql,list)
                cnx.commit()
                print("插入")
                i=0
                list.clear()
            i=i+1
        if i>0:
            cursor.executemany(sql,list)
            cnx.commit()
        cnx.close()
        f.close()
        print("ok")
    def listFiles(self):
        d = os.listdir("E:/data/")
        return d

           
if __name__ == "__main__":
    readFile = ReadFile()
    readFile.readLines()

相关文章

啥是佩奇?使用Python自动绘画小猪佩奇的代码实例

啥是佩奇?使用Python自动绘画小猪佩奇的代码实例

最近社会猪可是火遍了大江南北,不蹭下热度可对不起它。见过手画的佩奇,见过用代码画的吗? 没有?那就来看我大显身手。 用python的turtle库来画小猪佩奇。 有人问:turtle难不...

Python常用特殊方法实例总结

本文实例讲述了Python常用特殊方法。分享给大家供大家参考,具体如下: 1 __init__和__new__ __init__方法用来初始化类实例;__new__方法用来创建类实例。...

Python探索之修改Python搜索路径

当Python执行import语句时,它会在一些路径中搜索Python模块和扩展模块。可以通过sys.path查看这些路径,比如: >>> import sys...

Python pickle模块用法实例

python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,...

python中for循环把字符串或者字典添加到列表的方法

python中for循环把字符串或者字典添加到列表的方法

python中如何for循环把字符串添加到列表? 实例: 1.单个字符串用for循环添加到列表中: # 把L1中的字符串添加到列表alist里面 L1 = 'MJlifeBlog'...