#!/usr/bin/env python
import os
import commands
import time
import sys
def SqlOrder(SqlDir):
sqlfile={}
for i in os.popen(‘ls %s‘%SqlDir).readlines():
sqlfile[i] = i.split(‘-‘)[1]
sqlfile1=[]
for i in sorted(sqlfile.items(),key=lambda d:d[1]):
sqlfile1.append(i[0])
return sqlfile1
def MysqlDump(databasename):
datetime=time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
cmd=‘mysqldump -uroot -predhat %s >/test/%s_%s.sql‘%(databasename,databasename,datetime)
print cmd
k,v=commands.getstatusoutput(cmd)
#k,v=commands.getstatusoutput(‘mysqldump -uroot -predhat %s >/test/%s_%s.sql‘%(databasename,datetime))
if k == 0 :
return ‘MsyqlBackupSucess‘
else:
return ‘MysqlBackupFailed‘
def ImportSql(databasename,SqlDir):
test=SqlOrder(SqlDir)
done=MysqlDump(databasename)
if done ==‘MysqlBackupFailed‘:
return ‘mysqlbakcupfailed‘
for i in test:
#os.popen(‘mysql -uroot -predhat %s < /test/sql/%s‘%(databasename,i))
cmd=‘mysql -uroot -predhat %s < /test/sql/%s‘%(databasename,i.strip())
print cmd
k,v=commands.getstatusoutput(cmd)
#k,v=commands.getstatusoutput(‘mysql -uroot -predhat %s < /test/sql/%s‘%(databasename,i))
if k == 0:
print ‘%s import sql success‘%i
else:
print ‘%s import sql failed‘%i
return ‘importsqlfailed‘
if __name__ == "__main__":
DatabaseName=sys.argv[1]
SqlDir=sys.argv[2]
ImportSql(DatabaseName,SqlDir)
---------------------------------------------------------------------------------------------------------------
注意文件名格式和依赖的mysql命令就好,文件名格式:filesname-times.sql
这是一个根据多个SQL文件命名规范写了一个SQL批量导入的一个小脚本,
比如多个文件名如下:
a-20161021.sql
abc-20161020.sql
abcd-20161027.sql
b-20161022.sql
c-20161023.sql
d-20161024.sql
上面的脚本,可以根据后面的日期进行排序并导入到相应的数据库中
例子如下:
[[email protected] test]# python sqlUpdate2.py test /test/sql/
mysqldump -uroot -predhat test >/test/test_2010_12_12_14_16_26.sql
mysql -uroot -predhat test < /test/sql/f-20161020.sql
f-20161020.sql
import sql success
mysql -uroot -predhat test < /test/sql/f-20161021.sql
f-20161021.sql
import sql success
mysql -uroot -predhat test < /test/sql/g-20161022.sql
g-20161022.sql
import sql success