Python 練習(xí)冊 2-存儲激活碼到MySQL數(shù)據(jù)庫

Python 練習(xí)冊,每天一個小程序,原題來自Yixiaohan/show-me-the-code
我的代碼倉庫在Github

目標(biāo)

做為 Apple Store App 獨立開發(fā)者,你要搞限時促銷,為你的應(yīng)用生成激活碼(或者優(yōu)惠券),使用 Python 生成 200 個激活碼(或者優(yōu)惠券),并將激活碼保存到 MySQL 關(guān)系型數(shù)據(jù)庫中。

解決方案

該題目采用 python 中的 PyMySQL 模塊 來連接操作MySQL數(shù)據(jù)庫,代碼如下:

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


# 將0001題目中隨機生成的驗證碼保存到MySQL數(shù)據(jù)庫
import uuid
import pymysql


# 生成 num 個驗證碼,每個長度為length,可設(shè)置默認(rèn)長度
def create_num(num, length=16):
    result = []
    while num > 0:
        uuid_id = uuid.uuid4()
        # 刪去字符串中的'-',取出前l(fā)ength 個字符
        temp = str(uuid_id).replace('-', '')[:length]
        if temp not in result:
            result.append(temp)
            num -= 1
    return result
    
    
# 保存到MySQL數(shù)據(jù)庫
def save_to_mysql(code):
    conn = pymysql.connect(
        host='127.0.0.1', 
        port=3306, 
        user='root', 
        passwd=None, 
        db='test')
        
    try:
        with conn.cursor() as cursor:
            # Create a new record
            sql = "INSERT INTO `codes` (`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 `codes` 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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容