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 Json序列化与反序列化的示例

不同的编程语言有不同的数据类型; 比如说: Python的数据类型有(dict、list、string、int、float、long、bool、None) Java的数据类型有(boo...

Python Learning 列表的更多操作及示例代码

遍历列表-for循环 列表中存储的元素可能非常多,如果想一个一个的访问列表中的元素,可能是一件十分头疼的事。那有没有什么好的办法呢?当然有!使用 for循环 假如有一个食物名单列表,通过...

python django生成迁移文件的实例

关于Django生成迁移文件,我是在虚拟机上完成的 1.创建虚拟环境: 在终端上输入创建python3的虚拟环境 mkvirtualenv -p python3 虚拟环境的名字 在虚拟环...

对Django项目中的ORM映射与模糊查询的使用详解

ORM映射 什么是ORM映射?在笔者认为就是对SQL语句的封装,所写语句与SQL对应语句含义相同,使开发更加简单方便,不过也是存在弊端的,使程序运行效率下降。例如: UserInf...

pandas通过字典生成dataframe的方法步骤

1、将一个字典输入: 该字典必须满足:value是一个list类型的元素,且每一个key对应的value长度都相同: (以该字典的key为columns) >>>...