mysql遠程快速匯出csv格式資料工具

來源:互聯網
上載者:User

標籤:localtime   get   密碼   使用   指令碼語言   import   time   標準   use   

 如需轉載,請經本人同意。

之前本人曾經寫過一個使用 select ....into outfile原理匯出資料的指令碼,但該指令碼值適用於本地快速匯出,並不支援遠程服務,故又編寫了下面這個支援遠程匯出的指令碼。該指令碼支援匯出檔案檢測、資料庫資訊檢查。如果大家有好的建議歡迎留言評論。指令碼總體而言比較簡單,希望對大家有協助

指令碼語言:python

版本:2.7

#!/usr/bin/python# -*- coding:UTF-8 -*-#@author Jane.Hoo#@date 2016/11/29from __future__ import divisionimport osimport MySQLdbimport timeimport commandsimport loggingimport reimport mathprint ‘*******************************‘timestamp=time.strftime("%Y%m%d%H%M%S", time.localtime())logfile=‘/tmp/myloaddataout.log%s‘%timestamplogging.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層級或更高的日誌資訊列印到標準錯誤,並將其添加到當前的Tlog對象#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.pydb_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_flagif __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/ [人生不設限,生命不息,折騰不止] 您的支援是對博主最大的鼓勵,感謝您的認真閱讀。本文著作權歸作者所有,歡迎轉載,但請保留該聲明。

 

mysql遠程快速匯出csv格式資料工具

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.