Python-工具-生成测试数据
作者:互联网
在日常开发测试中,可能需要测试SQL执行性能,但是一般在开发环境中不存在测试所需的数据,因为生产环境的数据是有法律效益的,非法获取会触犯法律。
所以在平时的工作中只能自己根据数据标准造数据,为了避免重复编写造数脚本,编写了一个通用Python脚本。
import cx_Oracle import string import random def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) db=cx_Oracle.connect('用户名/密码@服务名') dbcursor = db.cursor() sql1 = 'insert into ' sql2 = ' values( ' bl = True while(bl==True): treemenuname = input('请输表名,0 退出\n') sql1 = sql1 + treemenuname + '(' num = input('请输生成条数,0 退出\n') dbcursor.execute("select col.column_name from user_constraints con, user_cons_columns col where con.constraint_name = col.constraint_name and con.constraint_type = 'P' and col.table_name = '%s' AND col.column_name <> 'CPCODE' and rownum<=1"%treemenuname) zj1 = dbcursor.fetchone() zj = zj1[0] print("主键关键字:",zj) if(treemenuname == '0'): break dbcursor.execute("select COLUMN_NAME,DATA_TYPE,DATA_LENGTH from user_tab_columns where TABLE_NAME = '%s' "%treemenuname) rs = dbcursor.fetchall() if(rs): for i in range(len(rs)): yz = rs[i] col = yz[0] typ = yz[1] lgh = yz[2] sql1 = sql1 + col if(zj != col): if(typ == 'VARCHAR2'): sql2= sql2 + "'" +id_generator(lgh)+"'" elif(typ == 'NUMBER'): sql2= sql2 + "%s"%i elif(typ == 'DATE'): sql2 = sql2 + "sysdate" else: sql2 = sql2 + "'主键'" zjlgh = lgh # if(len(rs) != i + 1): sql1 = sql1 + ',' sql2 = sql2 + ',' else: sql1 = sql1 + ')' sql2 = sql2 + ')' else: print("无查询结果") for i in range(int(num)): if(zj is not None): #print(sql2) dbcursor.execute(sql1 + sql2.replace('主键',id_generator(zjlgh))) db.commit() print("查询完成")
脚本保存为.py文件即可执行。
标签:string,constraint,Python,sql1,测试数据,生成,import,col,name 来源: https://www.cnblogs.com/yangjn/p/11635011.html