原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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/193605.html
標籤:Python
