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中的sort方法使用详解

Python中的sort()方法用于数组排序,本文以实例形式对此加以详细说明: 一、基本形式 列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法...

如何搜索查找并解决Django相关的问题

1. 卡住是怎么办 按照以下步骤, 前提是你需要懂点英文: 尽可能自己想办法解决 仔细阅读相关文档, 确保不错过任何相关内容 在Google, 百度, mailing lists或Sta...

django做form表单的数据验证过程详解

django做form表单的数据验证过程详解

我们之前写的代码都没有对前端input框输入的数据做验证,我们今天来看下,如果做form表单的数据的验证 在views文件做验证 首先用文字描述一下流程 1、在views文件中导入for...

介绍一款python类型检查工具pyright(推荐)

介绍一款python类型检查工具pyright(推荐)

近日,微软在 Github 上开源了一个 Python 静态类型检查工具:pyright ,引起了社区内的多方关注。 微软在开源项目上的参与力度是越来越大了,不说收购 Github 这种...

Python实现FTP上传文件或文件夹实例(递归)

本文实例讲述了Python实现FTP上传文件或文件夹实例。分享给大家供大家参考。具体如下: import sys import os import json from ftp...