python2中下载mysql数据库中的数据,并保存在csv文本中

本项目几个要点:
1.数据库中有中文,且为unicode编码,本项目环境为python2
2.数据库中时间字段为13位的字符型的时间戳,导出时需要改成正常的时间
3.导数需求为每一个小时导前一个小时的日志
4.导出后,涉及到将文件从此服务器转移到另一台服务器上(都是linux环境)
5.涉及到带密码的scp传输文件和python中执行shell命令


# -*- coding: utf-8 -*-

import MySQLdb as mdb
import codecs
import datetime
import time
import os

log_path='/data/log/sqllog_'

#log_file为日志文件,start_time为日志起始时间,end_time为日志结束时间
def get_start_time():
    dateFormat = "%Y-%m-%d %H:00:00"
    end_time = datetime.datetime.now().strftime(dateFormat)
    log_time = datetime.datetime.now().strftime("%Y%m%d%H")
    timeArray=time.strptime(end_time, "%Y-%m-%d %H:%M:%S")
    end_time=int(time.mktime(timeArray))*1000
    start_time=end_time-3600000
    log_file=log_path+log_time
    return log_file,start_time,end_time



def export_data(log_file,start_time,end_time):
    conn = mdb.connect(
        host = '192.168.1.11',
        user = 'username',
        passwd = 'passwd',
        db = 'dbname',
        port = 3306,
        charset = 'utf8'
    )
    
    cur = conn.cursor(mdb.cursors.DictCursor)
    sql = "select uid,pid,menuid,sid,pt,FROM_UNIXTIME(CONVERT(st/1000,signed),'%Y-%m-%d %T') as stime,FROM_UNIXTIME(CONVERT(et/1000,signed),'%Y-%m-%d %T') as etime from log_info where st>='"+str(start_time)+"' and st<'"+str(end_time)+"';"
    cur.execute(sql)
    rows=cur.fetchall()
    
    with codecs.open(log_file,'w','utf-8') as fh:
        for row in rows:
            fh.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" %(row["uid"],row["pid"],row["menuid"],row["sid"],row["pt"],row["stime"],row["etime"]))
            fh.write("\n")

    cur.close()
    conn.close()

#将文件转移到另一台服务器
def scp_file(log_file):
    cmd='sshpass -p passwd2 scp -P 22 '+ log_file+' [email protected]:/data/log'
    os.system(cmd)


if __name__=='__main__':
    log_file,start_time,end_time=get_start_time()
    export_data(log_file,start_time,end_time)
    scp_file(log_file)
    print("ok")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章