测试的工作中,经常会遇到项目交接或者搭建一个新的测试环境,而创建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表脚本 able.sql",r"E:SVN视图脚本view.sql")