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破解bilibili滑动验证码登录功能

python破解bilibili滑动验证码登录功能

地址:https://passport.bilibili.com/login 左图事完整验证码图,右图是有缺口的验证码图      &n...

python-Web-flask-视图内容和模板知识点西宁街

基本使用 #设置cookie值 @app.route('/set_cookie') def set_cookie(): response = make_response("...

Django模板导入母版继承和自定义返回Html片段过程解析

1.ROOT_URLCONF = '总路由所在路径(比如untitled.urls)'<===默认情况是这样 根路由的路径是可以修改的:ROOT_URLCONF = app01.u...

Python 字符串与二进制串的相互转换示例

一个问题,在Python中,如何将一个字符串转换为相应的二进制串(01形式表示),并且能够将这个二进制串再转换回原来的字符串。 一个简单版本 def encode(s): retu...

Python3.5局部变量与全局变量作用域实例分析

本文实例讲述了Python3.5局部变量与全局变量作用域。分享给大家供大家参考,具体如下: 1、局部变量与全局变量定义: 在子程序(函数)中定义的变量称为:局部变量;在程序顶级(一开始)...