Read and write python files and use mysql to insert examples in batches (use python to operate mysql)

Source: Internet
Author: User
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 ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.