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!")