# -*- coding: utf-8 -*-
import shutil,os
# 根据指定路径下的数据库备份文件生成还原脚本
def getFilesAndBuildSql(path,restorePath):
for root,dirs,files in os.walk(path):
for nfile in files:
if os.path.splitext(nfile)[1] == ".bak": # 筛选bak文件
dbName = os.path.splitext(nfile)[0]
logName = dbName + "_log"
# 创建数据还原脚本并写入文件
sqlFileName = 'C:\\Users\\merox-mac-win\\Desktop\\SqlRestore\\restore.sql'
with open(sqlFileName, 'a') as file_object:
file_object.write("--还原数据库{0}--\n".format(dbName).decode("utf-8").encode("utf-8"))
file_object.write("RESTORE DATABASE {0} FROM DISK = 'C:\\SqlRestore\\bak\\{1}' \n".format(dbName,nfile).decode("utf-8").encode("utf-8"))
file_object.write("WITH\n".decode("utf-8").encode("utf-8"))
file_object.write(" MOVE '{0}' TO '{2}\\{1}.mdf',\n ".format(dbName.replace("Kernel_HY_",""),dbName,restorePath).decode("utf-8").encode("utf-8"))
file_object.write(" MOVE '{0}' TO '{2}\\{1}.ldf'\n ".format(logName.replace("Kernel_HY_",""),logName,restorePath).decode("utf-8").encode("utf-8"))
file_object.write("GO\n\n".decode("utf-8").encode("utf-8"))
# 生成删除数据库脚本
with open('C:\\Users\\merox-mac-win\\Desktop\\SqlRestore\\drop.sql', 'a') as file_object:
file_object.write("--删除数据库{0}--\n".format(dbName).decode("utf-8").encode("utf-8"))
file_object.write("DROP DATABASE {0} \n".format(dbName).decode("utf-8").encode("utf-8"))
file_object.write("GO\n\n".decode("utf-8").encode("utf-8"))
# 控制台输出
print("RESTORE DATABASE {0} FROM DISK = 'C:\\{1}' ".format(dbName,nfile))
print("WITH")
print(" MOVE '{0}' TO '{2}\\{1}.mdf', ".format(dbName.replace("Kernel_HY_",""),dbName,restorePath))
print(" MOVE '{0}' TO '{2}\\{1}.ldf' ".format(logName.replace("Kernel_HY_",""),logName,restorePath))
print("GO")
print("")
# 创建发布文件夹
os.makedirs("C:\\Users\\merox-mac-win\\Desktop\\SqlRestore")
# 根据数据库备份文件目录生成还原脚本
getFilesAndBuildSql("C:\\Game_ZS\\Database\\dbbak","C:\\db")
# 生成还原BAT文件
with open("C:\\Users\\merox-mac-win\\Desktop\\SqlRestore\\restore.bat", 'a') as file_object:
file_object.write("md c:\\db\n".decode("utf-8").encode("utf-8"))
file_object.write("osql -E -i c:\\SqlRestore\\restore.sql\n".decode("utf-8").encode("utf-8"))
file_object.write("--还原数据库--\n".decode("utf-8").encode("gbk"))
for root,dirs,files in os.walk("C:\\Game_ZS\\Database\\dbbak\\link"):
for nfile in files:
print("osql -E -i c:\\{0}".format(nfile))
with open("C:\\Users\\merox-mac-win\\Desktop\\SqlRestore\\restore.bat", 'a') as file_object:
file_object.write("osql -E -i c:\\SqlRestore\\link\\{0}\n".format(nfile))
# 复制链接服务器脚本文件夹
shutil.copytree("C:\\Game_ZS\\Database\\dbbak\\link","C:\\Users\\merox-mac-win\\Desktop\\SqlRestore\\link")
# 复制bak备份文件
shutil.copytree("C:\\Game_ZS\\Database\\dbbak\\bak","C:\\Users\\merox-mac-win\\Desktop\\SqlRestore\\bak")
# 压缩数据发布文件夹
os.system("rar a restore.rar SqlRestore")
# 测试压缩文件
os.system("rar t restore.rar")
# 删除生成的发布目录
shutil.rmtree("C:\\Users\\merox-mac-win\\Desktop\\SqlRestore")