This article describes how to read and write python files and use mysql batch insert examples. you can learn how to operate a mysql database using python. For more information, see
The code is as follows:
#-*-Coding: UTF-8 -*-
'''
Created on December 9, 2013
@ Author: hhdys
'''
Import OS
Import mysql. connector
Config = {
'User': 'root ',
'Password ':'******',
'Host': '2017. 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 )"
If I> 5000:
Cursor.exe cute.pdf (SQL, list)
Cnx. commit ()
Print ("insert ")
I = 0
List. clear ()
I = I + 1
If I> 0:
Cursor.exe cute.pdf (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 ()