原GitHub地址:https://github.com/Yixiaohan/show-me-the-code
题目:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
代码:
import pymysql
import uuid
# 生成激活码,number为数量,length为长度
def generate_code(number, length):
codes = []
k = 0
while(True):
temp = str(uuid.uuid1()).replace("-", "")[:length]
if k == number:
break
elif temp not in codes:
codes.append(temp)
k += 1
else:
continue
return codes
# 保存到数据库
def save_to_mysql(codes):
# 创建数据库连接
connection = pymysql.connect(host='127.0.0.1', port=3306,
user='root', passwd='root',db='test', charset='utf8')
# 获取游标,我们使用游标来执行语句
cursor = connection.cursor()
# 创建表,设置其中的属性
cursor.execute('''CREATE TABLE IF NOT EXISTS codes(
id INT NOT NULL AUTO_INCREMENT,
code VARCHAR(32) NOT NULL,
PRIMARY KEY(id))''')
# 插入已经生成的激活码
for code in codes:
cursor.execute('INSERT INTO codes(code) VALUES(%s)', (code))
cursor.connection.commit()
connection.close()
if __name__ == '__main__':
codes = generate_code(20, 12)
save_to_mysql(codes)