五郎. 发表于 2018-8-21 13:36:32

Shell/Python实现Mysql读txt文本

#!/usr/bin/python  
# mysql_import.py
  

  
#使用MySQLdb去实现
  
import MySQLdb,os,time
  

  
os.system("sed -e 's/\"//g' -e 's#/#-#g' test.txt >t.txt");
  

  
try:
  
    print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))#记录开始时间
  
    conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='zhang1992')
  
    print "conn success"
  
except:
  
    print "conn error!"
  
    exit()
  
cur=conn.cursor()
  
cur.execute('drop database if exists myimport')
  
cur.execute('create database myimport')
  
i=0
  
count=0
  
with open('t.txt','r') as ft:
  
    for row in ft.readlines():
  
      ID,NAME,CREATED=list(row.strip("\n").split(","))
  
      if i==0:
  
            cid=ID
  
            cname=NAME
  
            created=CREATED
  
            cur.execute("create table if not exists myimport.import_obj(id int unsigned auto_increment primary key,%s int unsigned unique not null,%s varchar(60) not null,%s datetime not null)"%(ID,NAME,CREATED))
  
            i=1
  
      else:
  
            sql="insert into myimport.import_obj(%s,%s,%s) value(%d,'%s','%s')"%(cid,cname,created,int(ID),NAME,CREATED)
  
            cur.execute(sql)
  

  
os.system("rm -f t.txt")
  
cur.close()
  
conn.commit()
  
conn.close()
  

  
print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))#记录结束始时间


页: [1]
查看完整版本: Shell/Python实现Mysql读txt文本