Python 每日练习 03 把将随机生成的200 个激活码保存在mysql中

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


# 将0001题目中随机生成的200个验证码保存到MySQL数据库
import uuid
import pymysql


# 生成 num 个验证码,每个长度为length,可设置默认长度
def create_num(num, length=16):
    result = []
    while num > 0:
        uuid_id = uuid.uuid4()
        # 删去字符串中的'-',取出前length 个字符
        temp = str(uuid_id).replace('-', '')[:length]
        if temp not in result:
            result.append(temp)
            num -= 1
    return result


# 保存到MySQL数据库
def save_to_mysql(code):
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='1469',
        db='test')

    try:
        with conn.cursor() as cursor:
            # Create a new record
            sql = "INSERT INTO `activation` (`code`) VALUES (%s)"
            cursor.execute(sql, code)

        # connection is not autocommit by default. So you must commit to save
        # your changes.
            conn.commit()

        with conn.cursor() as cursor:
            # Read a single record
            sql = "SELECT `id`, `code` FROM `activation` WHERE `code`=%s"
            cursor.execute(sql, code)
            result = cursor.fetchone()
            print(result)
    finally:
        conn.close()

for code in create_num(200):
    save_to_mysql(code)

你可能感兴趣的:(Python)