ITPub博客

首页 > IT职业 > IT图书 > python如何导入txt数据库?

python如何导入txt数据库?

IT图书 作者:samenzhou 时间:2021-09-11 10:15:02 0 删除 编辑

python将TXT数据导入数据库的方法代码如下:

#!/usr/bin/python
#coding=utf-8

import _mysql,sys,time
#读入数据函数
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()
	#读出第一行数据,作为数据表的段名
    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(90),%s varchar(90),%s varchar(90))"%(content[0][1:-1],content[1][1:-1],content[2][1:-1]))
    conn0.close()
    #运用next函数,让for循环从第二行开始读数据
    next(f)
    for line in f:
	   #做一些处理,让每一段分开,放置在一个列表中
       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)

更多Python知识请关注Python自学网

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/912/viewspace-2833351/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    104
  • 访问量
    1057