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