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使用正则表达式匹配字符串开头并打印示例

本文实例讲述了python使用正则表达式匹配字符串开头并打印的方法。分享给大家供大家参考,具体如下: import re s="name=z1hangshan username=ff...

tensorflow实现简单的卷积网络

使用tensorflow实现一个简单的卷积神经,使用的数据集是MNIST,本节将使用两个卷积层加一个全连接层,构建一个简单有代表性的卷积网络。 代码是按照书上的敲的,第一步就是导入数据库...

致Python初学者 Anaconda入门使用指南完整版

打算学习 Python 来做数据分析的你,是不是在开始时就遇到各种麻烦呢? 到底该装 Python2 呢还是 Python3 ? 为什么安装 Python 时总是出错? 怎么安装工具包呢...

python网络编程学习笔记(一)

学习用书:《python 网络编程基础》作者John Goerzen 第一部分底层网络学习         Pyth...

PYTHON绘制雷达图代码实例

PYTHON绘制雷达图代码实例

这篇文章主要介绍了PYTHON绘制雷达图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、雷达图 import matp...