python每日一练:0002题

第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

示例代码:

import os
import string
import random
import pymysql

def main():
    config = {
    'host': '192.168.3.222',
    'port': 3306,
    'user': 'root',
    'password': 'root',
    'db': 'test',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor,
    }
    conn = pymysql.connect(**config)    #建立数据库连接
    rowId = 0
    if os.path.exists('./activateCode.txt'):
        os.remove('./activateCode.txt')
        print("重新生成激活码文件!")
    chars = string.ascii_letters + string.digits    #a-zA-Z0-9
    codeNumber = int(input("请输入需要生成的激活码数量:"))
    codeLength = int(input("请输入需要生成的激活码长度:"))
    if codeNumber == '':
        codeNumber = 10
    if codeLength == '':
        codeLength = 8
    for i in range(codeNumber):
        code = random.choices(list(chars),k=codeLength)
        with conn.cursor() as cursor:
            sql = "insert into CODES (id,number) values(%s,%s)"
            cursor.execute(sql,(str(rowId),''.join(code)))  #执行sql语句
            conn.commit()   #提交数据库
            rowId += 1
    conn.close()    #关闭连接


if __name__ == "__main__":
    main()

猜你喜欢

转载自www.cnblogs.com/xuxiaowen1990/p/11225414.html