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

相关文章

Python3 能振兴 Python的原因分析

我从Stephen A. Goss那读到关于了《Python 3正在毁灭Python》。这篇文章有不少精彩的论点,但我却并不认为Python 3是在毁灭Python,也不认为整个局面对P...

python中as用法实例分析

本文实例讲述了python中as用法。分享给大家供大家参考。具体分析如下: import some # some 为一个模组 如果想要改变被导入模组在当前模组中的名称,而不是sys...

Python 正则表达式入门(初级篇)

引子 首先说 正则表达式是什么? 正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regular Expression,在代码中常简写为regex、re...

详解JavaScript编程中的window与window.screen对象

Window 对象 所有浏览器都支持 window 对象。它表示浏览器窗口。 所有 JavaScript 全局对象、函数以及变量均自动成为 window 对象的成员。 全局变量是 win...

理解Python垃圾回收机制

一.垃圾回收机制 Python中的垃圾回收是以引用计数为主,分代收集为辅。引用计数的缺陷是循环引用的问题。 在Python中,如果一个对象的引用数为0,Python虚拟机就会回收这个对象...