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

yipeiwu_com5年前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定义一个跨越多行的字符串的多种方法小结

方法一: >>> str1 = '''Le vent se lève, il faut tenter de vivre. 起风了,唯有努力生存。 (纵有疾风起,人...

视频合并时使用python批量修改文件名的方法

视频合并时使用python批量修改文件名的方法

不知道大家有没有遇到这样的情况,比如视频合并时文件名没有按照正常顺序排列,像这样    可见,文件名排序是乱的。这个样子合并出来的视频一定也是乱的。所以得想办法把文件...

django admin后台添加导出excel功能示例代码

django admin后台添加导出excel功能示例代码

Django功能强大不单在于他先进的编程理念,很多现有的功能模块更是可以直接拿来使用,比如这个牛掰的admin模块,可以作为一个很好的信息登记管理系统。 admin模块中的actioin...

python和mysql交互操作实例详解【基于pymysql库】

python和mysql交互操作实例详解【基于pymysql库】

本文实例讲述了python和mysql交互操作。分享给大家供大家参考,具体如下: python要和mysql交互,我们利用pymysql这个库。 下载地址: https://github...

Python计算一个文件里字数的方法

本文实例讲述了Python计算一个文件里字数的方法。分享给大家供大家参考。具体如下: 这段程序从所给文件中找出字数来。 from string import * def countW...