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通过Windows下远程控制Linux系统

python通过Windows下远程控制Linux系统

一、学习目标 【通过Windows下远程控制Linux系统实现对socket模块认识】 二、实验环境 Windows下(模拟客户端 [ IP:192.168.43.87 ] ):pyth...

在Python中使用全局日志时需要注意的问题

在使用 uliweb 开发 soap webservice 后,启动 uliweb 时,werkzeug 的日志莫名其妙丢失了。 正常的日志: 复制代码 代码如下:[INFO] ...

python映射列表实例分析

本文实例讲述了python映射列表。分享给大家供大家参考。具体分析如下: 列表映射是个非常有用的方法,通过对列表的每个元素应用一个函数来转换数据,可以使用一种策略或者方法来遍历计算每个元...

用pickle存储Python的原生对象方法

在Python中存储数据到文件中时,简单的做法是调用open函数执行文件写入操作,但是这样做的话,当我们要重新读取文件内容时,就会出现类型不匹配的情况,因为读取的都是字符串的形式,所以还...

Laravel+Dingo/Api 自定义响应的实现

在最近的开发开发项目中,我使用了Dingo/Api这个第三方Api库。 Dingo是个很强大的Api库, 但在开发的过程中,需要自定义响应字段。 刚开始使用Ding/Api时,返回如下...