測試的工做中,常常會遇到項目交接或者搭建一個新的測試環境,而建立oracle數據庫用戶及表空間時,須要提早找出腳本中的
數據庫用戶名和表空間名,因此本身寫了一個python腳本,自動找出sql腳本中的數據庫用戶名和表空間名以及對應出現的次數。
腳本以下:
#encoding=utf-8
import re
def FindUsernameOrTableplace(*dir_part):
username_num={}
tablespace_num={}
try:
for i in dir_part:
print(i)
with open(i,"r",encoding="utf-8") as ft:
while 1:
line=ft.readline()
if line=="":
break
else:
line=line.split()
#使用正則匹配出該行中以table開頭,而且table後面鏈接空格的行,或table先後都是鏈接空格的行
if re.search(r"(?<= )(table)(?= )"," ".join(line)) or \
re.search(r"(table)(?= )"," ".join(line)):
if line.index("table")+1<len(line): #判斷table不在末尾的行
if "." in line[line.index("table")+1]:
username=line[line.index("table")+1].split(".")[0]
if username not in username_num.keys():
username_num[username]=1
elif username in username_num.keys():
username_num[username]+=1
elif re.search(r"(?<= )(tablespace)(?= )"," ".join(line)) or \
re.search(r"(tablespace)(?= )"," ".join(line)):
if line.index("tablespace")+1<len(line):
if line[line.index("tablespace")+1] not in tablespace_num.keys():
tablespace_num[line[line.index("tablespace")+1]] = 1
elif line[line.index("tablespace")+1] in tablespace_num.keys():
tablespace_num[line[line.index("tablespace") + 1]]+=1
elif re.search(r"(?<= )(view)(?= )"," ".join(line)) or \
re.search(r"(view)(?= )"," ".join(line)):
if line.index("view")+1<len(line):
if "." in line[line.index("view")+1]:
username=line[line.index("view")+1].split(".")[0]
if username not in username_num.keys():
username_num[username]=1
elif username in username_num.keys():
username_num[username]+=1
print("數據庫(用戶)角色及出現數量:",username_num)
print("表空間及出現數量::",tablespace_num)
except Exception as err:
print(err)
if __name__=="__main__":
FindUsernameOrTableplace(r"E:\SVN\表腳本\table.sql",r"E:\SVN\視圖腳本\view.sql")