Python TXT data Import Database

Source: Internet
Author: User
Tags import database

To import data, you can do some processing of the data to make it easier to import the database #!/usr/bin/python#coding=utf-8import _mysql,sys,time# read into the data function Def add_data ( Id,name,created_time):     try:        conn=_ Mysql.connect (' 127.0.0.1 ', ' root ', ')         conn.query ("Set names  utf8 ")         conn.query (" Insert into mysql.test3 (%s,% s,%s)  values ('%s ', '%s ', '%s ') "% (' object_id ', ' object_name ', ' created ', id,name,created_time))          result=conn.use_result ()          Conn.close ()     except _mysql. error,e:        print  ("error %d:%s"  %  (e.args[0), E.ARGS[1])         sys.exit (1) if __name__ == "__main__":     f= open ("/opt/testdata/aaa.txt", "R")      time1=time.time ()     print time.ctime () #读出第一行数据, as the segment name of the datasheet      line=f.readline ()     content=line.strip (). Split (",")     conn0=_ Mysql.connect (' 127.0.0.1 ', ' root ', ')     print  ' connection is builded  succesfully '     conn0.query ("Drop table if exists mysql.test3")      conn0.query ("Create table mysql.test3 (%s varchar),%s varchar (+),%s  varchar (+)) "% (Content[0][1:-1],content[1][1:-1],content[2][1:-1]))     conn0.close ()      #运用next函数, let the For loop begin reading the data from the second line     next (f)     for  line in f:    #做一些处理, make each paragraph separate, placed in a list         Content=line.strip (). Split (",")        add_data (id=content[0][1:-1],name= Content[1][1:-1],created_tiMe=content[2][1:-1])            f.close ()      time2=time.time ()     print time.ctime () #计算导入数据的时间      print  ' importing time is %f '% (time2-time1)


This article is from the "Demonzhuang" blog, make sure to keep this source http://demonzhuang.blog.51cto.com/11973722/1840305

Python TXT data Import Database

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.