python 介面自動化測試--程式碼實現(七)
阿新 • • 發佈:2019-02-19
資料庫還原指令碼:
#! /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