python实现数据库的批量新增
代码实现
import pymysql
import random
name_list=["周","武","郑","王","赵","钱","孙","李"]
m_list=["静静","思思","雯雯","夏夏","蓝蓝","三","飞","索隆","三治","娜美","索普","尚香"]
sex_list=["男","女"]
home_list=["平顶山","河南","上海","北京","菏泽","河北"]
db=pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456",databases='1')
# 用connec方法连接数据库 host:本机地址 port:端口号 user:用户名 passwd:密码
# database:要操作的数据库
cursor=db.cursor(cursor=pymysql.cursors.DictCursor)# 创建游标
for i in range(20): # 批量新增20条数据
n=random.randint(0,len(name_list)-1)#生成姓下标
m=random.randint(0,len(m_list)-1)#生成名下标
name=name_list[n]+m_list[m]
sexnum=random.randint(0,1)
sex=sex_list[sexnum]
age=random.randint(1,100)
homenum=random.randint(0,len(home_list)-1)
home=home_list[homenum]
high = random.uniform(1,100) # 生成随机身高
sql = "insert into `student` (name,age,sex,home,high) values ('{}','{}','{}','{}','{}')".format(name,age,sex,home,high)
# sql新增数据
cursor.execute(sql) # 执行sql语句
db.commit() # 新增完之后要更提交给数据库
cursor.close() # 关闭游标
db.close() # 关闭数据库
实现效果
尾部小结
在实现梦想的路上,不要停下前进的脚步,要保持热情和毅力,不断奋斗、不断拼搏,用汗水浇灌心中的种子,让自己在追梦的路上绽放出最耀眼的光芒。