# -*- coding=utf-8 -*- import pyodbc from datetime import datetime import pymssql import decimal class SQLServer: def __init__(self,server,user,password,database,autocommit): self.server = server self.user = user self.password = password self.database = database self.autocommit = autocommit def __GetConnect(self): if not self.database: raise(NameError,"没有数据库信息") self.conn = pymssql.connect(server=self.server,user=self.user,password=self.password,database=self.database,autocommit=self.autocommit) cur = self.conn.cursor() if not cur: raise(NameError,"连接数据库失败") else: return cur def restoreDb(self,database,restorepath): cur = self.__GetConnect() restorePath = restorepath + database + datetime.now().strftime("%Y%m%d") + '.bak' sql = "RESTORE DATABASE [{0}] FROM DISK = N'{1}' WITH FILE=1,Replace,stats = 10".format(database,restorePath) cur.execute(sql) self.conn.close() def main(): msg = SQLServer(server="192.168.2.190",user="sa",password="P123",database="master",autocommit=True) msg.restoreDb("wanghz","D:\backup\") if __name__ == "__main__": main()