创建学生表,用python随机生成姓名,性别,班级,省,市,生日插入数据库中
先把姓名和省市以字典方式存入单独文件
from name_dict import name from city_dict import city from random import choice,randint from datetime import date import psycopg2 as pg conn=pg.connect(database='school',user='jm',password='123',host='127.0.0.1',port='5432') cur=conn.cursor() date1=date(1975,1,1) date2=date(1977,12,31) days=(date2-date1).days class_x=['1班','2班','3班','4班','5班','6班','7班','8班'] k1=k2=k3=k4=k5=k6=k7=k8=0 #每班学生不超过50人 for i in range(1000): #=====省市============ 省=choice(list(city.keys())) 市=choice(city[省]) if 省=='直辖市': 省=choice(city['直辖市']) 市=省 if 省=='特别行政区': 省=choice(city['特别行政区']) 市=省 #=====姓名========= 性别=choice(['男','女']) if 性别=='男': 姓名=choice(name['姓'])+choice(name['男名']) else: 姓名=choice(name['姓'])+choice(name['女名']) #=====生日========= 生日=date1+date.resolution*randint(0,days) #=====班级========= 班级=choice(class_x) if 班级=='1班' : k1+=1 if k1==50: class_x.remove('1班') elif 班级=='2班' : k2+=1 if k2==50: class_x.remove('2班') elif 班级=='3班' : k3+=1 if k3==50: class_x.remove('3班') elif 班级=='4班' : k4+=1 if k4==50: class_x.remove('4班') elif 班级=='5班' : k5+=1 if k5==50: class_x.remove('5班') elif 班级=='6班' : k6+=1 if k6==50: class_x.remove('6班') elif 班级=='7班' : k7+=1 if k7==50: class_x.remove('7班') elif 班级=='8班' : k8+=1 if k8==50: class_x.remove('8班') if len(class_x)==0: break
#插入数据到数据库中 cur.execute('insert into student_basic\d(姓名,性别,班级,省,市,生日) values(%s,%s,%s,%s,%s,%s)',(姓名,性别,班级,省,市,生日))
conn.commit() cur.close() conn.close() print('ok')
标签:班级,python,psycopg2,50,remove,choice,elif,pg,class From: https://www.cnblogs.com/jm7612/p/17506411.html