Python Execute mysqldump command

Source: Internet
Author: User

This article briefly describes how to execute some SQL statements using Python, such as executing the mysqldump command, making a database backup, and backing up the SQL file#!/usr/bin/python
#导入os模块
Import OS
#导入时间模块
Import Time
#导入sys模块
Import SYS
#追加mysql的bin目录到环境变量
sys.path.append (' C:\Program Files (x86) \mysql\mysql Server 5.5\bin ')

#如果不存在backup文件, create a new
if not os.path.exists (' backup '):
os.mkdir (' backup ')
#切换到新建的文件夹中
os.chdir (' backup ')
#def Tuplesql (command,server,user,passwd,db,table,filename):
# return (mysqlcomm,dbserver,dbuser,dbpasswd,dbname,dbtable,exportfile)
#定义一系列参数
mysqlcomm= ' mysqldump '
dbserver= ' xxxx.xxxx.com '
dbuser= ' xxxxxxx '
dbpasswd= ' xxxxxxxxxxxxxxxxxxxxxxxx '
dbname= ' xxxxxx '
dbtable= ' xxxxx '
exportfile= ' Xxxx.sql '
#定义sql的格式
sqlfromat= "%s-h%s-u%s-p%s%s%s >%s"
#生成相应的sql语句
sql= (sqlfromat% (mysqlcomm,dbserver,dbuser,dbpasswd,dbname,dbtable,exportfile))

#判断是否已经有相应的sql文件生成; If so, rename the file by Time
if os.path.exists (R ' Qiang.sql '):
print (Time.ctime ())
os.rename (' Qiang.sql ', ' Qiang ' +str (Time.time ()) + '. sql ')
print (' Qiang ' +str (time.time) + '. sql ')
#执行sql并获取语句, Os.system and Subprocess.popen execute the SQL without effect, do not know what is going on, follow-up will continue to follow
result=os.popen (SQL)
#对sql执行进行判断
If result:
print ("Backup completed!")
Else:
print ("I ' m sorry!!!, backup failed!")
Related Article

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.