數據庫還原腳本:
#! /usr/bin/python # coding:utf-8 import time from Engine.SqlEngine import MSSQL COUNT=1 def restoreRelease(): global COUNT checkConSql = "select spid from sysprocesses where dbid in (select dbid from sysdatabases where name='SOATest')" restoreSql = "RESTORE DATABASE SOATest FROM DATABASE_SNAPSHOT = 'SOATest_ss'" dbc=MSSQL('192.168.1.2','yht','yht','Master') conNum = dbc.ExecQuery(checkConSql) if COUNT < 5: if len(conNum) == 0: print(u'%d條連接數,可以還原數據庫,還原中...'%len(conNum)) dbc.ExecNonQuery(restoreSql) print(u'數據庫還原完成') return True else: print(u'%d條連接數占用無法還原數據庫,5秒后重試'%len(conNum)) time.sleep(5) COUNT=COUNT+1 restoreRelease() else: print(u'%d條連接數始終占用,已試過5次依然無法還原數據庫'%len(conNum)) return False
SqlEngine.py
#! /usr/bin/python # coding:utf-8 import pymssql import sys from Engine.DataEngine import decoCatchExcep reload(sys) sys.setdefaultencoding('utf-8') class MSSQL(object): """ 對pymssql的簡單封裝 pymssql庫,該庫到這里下載:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql 使用該庫時,需要在Sql Server Configuration Manager里面將TCP/IP協議開啟 用法: """ def __init__(self,host,user,pwd,db): self.host = host self.user = user self.pwd = pwd self.db = db def __GetConnect(self): """ 得到連接信息 返回: conn.cursor() """ if not self.db: raise(NameError,"沒有設置數據庫信息") self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") cur = self.conn.cursor() if not cur: raise(NameError,"連接數據庫失敗") else: return cur @decoCatchExcep def ExecQuery(self,sql): cur = self.__GetConnect() cur.execute(sql) resList = cur.fetchall() self.conn.close() return resList @decoCatchExcep def ExecNonQuery(self,sql): cur = self.__GetConnect() self.conn.autocommit(True) cur.execute(sql) self.conn.autocommit(False) self.conn.commit() self.conn.close()
裝飾器decoCatchExcep:
def decoCatchExcep(func): def _decoCatchExcep(*args, **kwargs): try: ret = func(*args, **kwargs) return ret except Exception,e: print(func.__name__+' : '+str(e).encode('gb18030')) LogPro.writeException(str(e).encode('gb18030')) return _decoCatchExcep