python的mysql --练习题

题目
随机生成100个人名和对应的密码;
人名由三个汉字或者2个汉字组成,
姓 = [许, 张, 赵, 钱, 孙, 李, 朱, 杨]
名 = [彬, 群, 宁, 盼, 龙, 欢, 丹]
密码统一6位, 由字母和字符组成;
存储上述用户信息到数据库中,
保存在数据库users中的userinfo表中;

编程

import random
from random import choice as choice
import string
import pymysql
# 生成指定位数密码, 前 n-1 位为数字, 最后一位为密码 ;
def create_passwd(count=6):
    nums = random.sample(string.digits, count - 1)
    letters = random.sample(string.ascii_letters, 1)
    return "".join(nums + letters)

a = create_passwd()
print(a,type(a))
# 生成随机的姓名, 有两个或三个汉字组成 ;
def create_name():
    first = ['许', '张', '赵', '钱', '孙', '李', '朱', '杨']
    second = ['彬', '群', '宁', '盼', '龙', '欢', '丹']
    last = ['彬', '群', '宁', '盼', '龙', '欢', '丹', ' ' ]
    name = choice(first) + choice(second)+ choice(last)
    return name.rstrip()
def main():

    # 1.连接数据库 host user passwd charset
    conn = pymysql.connect(host='localhost',
                       user='root',
                       password='redhat',
                       db='westos',
                       charset='utf8'
    )


    # 2.创建游标对象
    cur = conn.cursor()
    n = int(input("生成数据数:"))
    # 往数据库表中插入 n 条随机数据 ;
    for i in range(n):
    # cur.execute('insert into userinfo values("user1", "123");')
        sqli = 'insert into userinfo values ("%s", "%s");' %(create_name(), create_passwd())
        cur.execute(sqli)
        # 提交数据,并关闭连接 ;
    conn.commit()
    cur.close()

main()

发布了103 篇原创文章 · 获赞 1 · 访问量 952

猜你喜欢

转载自blog.csdn.net/qq_45652989/article/details/103951527