Python Imports a database script

Source: Internet
Author: User

The script for bulk import data SQL file, the data directory holds the SQL file to import, List.txt hold the list information to import.

The script reads as follows:

#!/usr/bin/env python# -*- coding:utf-8 -*-import os, sys, logging,  datetime#  log file Configuration If not os.path.isdir (' logs '):     os.mkdir (' logs ') Logging.basicconfig (level=logging.info,                     format= '% (asctime) s % (name) -12s % (levelname)- 8s % (message) s ',                     datefmt= '%y-%m-%d %h:%m ',                     filename= ' Logs/importable.log ',                      filemode= ' a ') console = logging. Streamhandler () console.setlevel (Logging.info) formatter = logging. Formatter ('% (message) s ') Console.setformatter (formatter) Logging.getlogger ("). AddHandler (console) logger =  Logging.getlogger (__name__) #  read host list information from local configuration file Def readinfo (confile):     info_list  = []    if os.path.isfile (Confile):         with open (confile,  ' r+ ')  as f:             for line in f.readlines ():                 if not line.startswith ("#"):                     dict  = {}                     dict[' id '] = line.split () [0]                     dict[' host '] = line.split () [1]                     dict[' name '] =  line.split () [2]                     info_list.append (dict)              return info_list    else:         logger.error (u "local config file%s does not exist!) " % confile)         sys.exit (1) def readsqlfile (data):     sql_list = []    #  determine if the local SQL file exists for the directory.     if os.path.isdir (data):        for  Sql_file in os.listdir (data): &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;if sql_file:                 sql_list.append (Os.path.join (data,sql_file))              else:               There are no SQL files to import in the   logger.error (U "local%s directory!) "%data)     else:        logger.error (U"%s  is not a directory. "%data)     return sql_list#  loop info_list and sql_list import SQL into each server def importhost ( Info_list, sql_list):     succ_list = []    fail_list  = []    for ser in info_list:         for sql_file in sql_list:             cmd =  "%s/mysql -u%s -p%s -h '%s '  %s < %s " %  (mysql_path, mysql_user, mysql_passwd, ser[' host '], ser[') Name '] ,sql_file)             status =  os.system (CMD)             if status  == 0:                 msg =  "%s -- %s -- %s  Import sql:%s  finished! "% (ser[' id '],ser[' host '],ser[' name '],sql_file)                  succ_list.append (msg)                  logger.info (msg)              else:                 msg =  "%S&NBSP;--&NBSP;%S&NBSP;--&Nbsp;%s  Import sql:%s  failed! " %  (ser[' id '], ser[' host '], ser[' name '], sql_file)                  fail_list.append (msg)                  logger.error (msg)                  sys.exit (1)      return succ_list,fail_listdef yesorno (confile,data):    print  " The database list is as follows: "    info_list = readinfo (confile)     for ser  in info_list:        print  "%s --- %s - --- %s "% (ser[' id '],ser[' host '],ser[' name '])     iput = raw_input (" If you want to import the SQL file  %s, enter Yes or no: " %  (Os.listdir (data))     while  true:&nBsp;       if iput.lower ()  in [' y ', ' yes ']:             print  "You have chosen to continue the program action!" "            break         elif iput.lower ()  in [' n ', ' no ']:             print  "You chose to quit the program action!"             sys.exit (1)          else:            print   "You entered an illegal character, the script did not perform any action to import the SQL file, the program is about to exit." "            sys.exit (1) if __name__ ==   ' __main__ ':    #  basic information configuration variable     data = r ' data '   #  directory where local SQL files are stored     confile =  ' list. txt '  #  store server list information, format such as:  id  host dbname : 1 192.168.2.20 game _name_cn1    # mysql variables     mysql_path =  '/usr/local/ Mysql/bin '     mysql_user =  ' root '     mysql_passwd =   ' XIREXRT,MF '     yesorno (confile,data)     startime =  Datetime.datetime.now ()     sql_list = readsqlfile (data)      Info_list = readinfo (Confile)     succ,fail= importhost (info_list,sql_list)     logger.info (U ' total execution succeeded '%s ' . \r\n  total failed%s bar. '% ( Len (SUCC),  len (fail)))     endtime = datetime.datetime.now ()      logger.info (U "\r\ntotal time: %s ms"  %  (endtime - startime). microseconds / 1000))


This article is from the "-= lake-side Bamboo =-" blog, please be sure to keep this source http://bronte.blog.51cto.com/2418552/1911324

Python Imports a database script

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.