人生不设限

导航

mysql远程快速导出csv格式数据工具

 如需转载,请经本人同意。

之前本人曾经写过一个使用 select ....into outfile原理导出数据的脚本,但该脚本值适用于本地快速导出,并不支持远程服务,故又编写了下面这个支持远程导出的脚本。该脚本支持导出文件检测、数据库信息检查。如果大家有好的建议欢迎留言评论。脚本总体而言比较简单,希望对大家有帮助

脚本语言:python

版本:2.7

#!/usr/bin/python
# -*- coding:UTF-8 -*-
#@author Jane.Hoo
#@date 2016/11/29

from __future__ import division
import os
import MySQLdb
import time
import commands
import logging
import re
import math

print '*******************************'
timestamp=time.strftime("%Y%m%d%H%M%S", time.localtime())
logfile='/tmp/myloaddataout.log%s'%timestamp
logging.basicConfig(level=logging.DEBUG,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename='%s'%logfile,
        filemode='w')
print '导出日志记录在:%s'%logfile

#################################################################################################
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################
#python /cygdrive/c/Users/Jane.Hoo/PycharmProjects/loaddata/MySQLloaddataout.py
db_host='127.0.0.1'
db_user='test'
db_pwd='test'
db='test'
db_port=int('3306')

class Toolloadout:
    def __init__(self,pathfile=0):
        self.pathfile=pathfile

    #得到数据库连接
    def getdbconn(self,DB_HOST=db_host,DB_USER='routeload',DB_PWD='routeload',DB='test01',DB_PORT='3306'):
        logging.debug('%s:%s:%s:%s:%s'%(DB_HOST,DB_USER,DB_PWD,DB,DB_PORT))
        conn='unlink'
        try:
            conn=MySQLdb.connect(host=DB_HOST,user=DB_USER,passwd=DB_PWD,port=int(DB_PORT),db=DB)
            logging.info('数据库连接成功')
        except MySQLdb.OperationalError,e:
            logging.warning('数据库连接失败!%s'%e)
        return conn
    #关闭数据库连接
    def closedbconn(self,conn=0):
        logging.debug('闭数据库连接')
        conn.close()
    #检查导出文件
    def chekpathfile(self):
        pathfile=self.pathfile
        check_flag=0
        iffile_exists=os.path.exists(pathfile)
        if iffile_exists==1:
            check_flag=1
            logging.info('导出文件已存在!')
        else:
            path=os.path.split(pathfile)[0]
            ifpath_exists=os.path.isdir(path)
            if ifpath_exists==1:
                logging.info('%s是有效的路径'%path)
            else:
                check_flag=1
                logging.info('%s是无效的路径'%path)
        return check_flag

if __name__=='__main__':
    print '准备导出...'
    pathfile=raw_input("请输入导出文件路径:").strip()
    cmd_sql=raw_input('请输入要查询的语句:').strip()
    c=Toolloadout(pathfile)
    pf_check=c.chekpathfile()
    if pf_check==0:
        logging.info('文件路径校验通过')
    ifinputdbmsg=raw_input('是否需要自定义数据库连接信息(Y|N)?').strip()
        if ifinputdbmsg=='Y':
            db_host=raw_input('请输入数据地址:').strip()
            db_user=raw_input('请输入用户名:').strip()
            db_pwd=raw_input('请输入密码:').strip()
            db=raw_input('请输入数据库名:').strip()
            db_port=raw_input('请输入数据库端口:').strip()
            if db_host=='' or db_user=='' or db_pwd=='' or db=='':
                logging.info('自定义数据库输入信息有为空.')
                check_flag=1
            if_port=re.match(r"[0-9]", db_port)
            if if_port:
                db_port=int(db_port)
            else:
                db_port=int('3306')
                logging.info('端口格式输入有误,将使用默认端口%s'%db_port)
        conn=c.getdbconn(db_host,db_user,db_pwd,db,db_port)
    if str(conn)!='unlink':
            selectsql="mysql -A %s -h %s -u%s -p%s -P%s -ss -e '%s;' | sed 's/\\t/,/g;s/^//;s/$//;s/\\n//g' >%s"%(db,db_host,db_user,db_pwd,db_port,cmd_sql,pathfile)
        print 'querysql:',selectsql
        try:
            os.system('%s'%selectsql)
        except BaseException,e:
        logging.info('导出数据过程中报错!%s'%e)
            c.closedbconn(conn)
    else:
        logging.info('失败')
    else:
        logging.info('文件路径校验不通过,导出结束')

 

作者:jane.hoo 
出处:jane.hoo的博客 http://www.cnblogs.com/janehoo/ 
[人生不设限,生命不息,折腾不止] 
您的支持是对博主最大的鼓励,感谢您的认真阅读。本文版权归作者所有,欢迎转载,但请保留该声明。

 

posted on 2016-11-29 16:25  风的_理想  阅读(1631)  评论(0编辑  收藏  举报