Python 練習冊,天天一個小程序 -- 0002題

有段時間沒寫博客了,繼續寫練習題python

第 0002 題:將 0001 題生成的 200 個激活碼(或者優惠券)保存到 MySQL 關係型數據庫中。mysql


分析問題:git

因爲是要把數據保存到mysql中,這裏就須要用到MySQLdb模塊,而且先生成再存入,sql

注意:數據庫

1 這裏操做MySQL的時候,先寫入一條,得到id,而後再更新該條記錄dom

2  建立的驗證碼的格式爲---'16進制的sql_id' + 'L' + 隨機碼ide

上代碼:post

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import datetime
import random
import string
def opt_mysql(num):
    conn = MySQLdb.connect(user='root',passwd='ssp123',port=3306,charset="utf8",db='python')
    cur = conn.cursor()
    drop_table = '''DROP TABLE IF EXISTS lol_code'''
    cur.execute(drop_table)
    create_table = '''
        CREATE TABLE lol_code(
        id   INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
        codes VARCHAR(64) NOT  NULL ,
        create_time VARCHAR(64) NOT  NULL );
    '''
    cur.execute(create_table)
    for i in range(num):
        create_time = datetime.datetime.now()
        insert_table = '''INSERT INTO lol_code(codes,create_time) VALUES('TestCode','%s')'''%create_time
        cur.execute(insert_table)
        id = conn.insert_id() #conn.insert_id()必定要在conn.commit()以前,不然會返回0
        code = create_code(id)
        update_table ='''UPDATE lol_code SET codes = '%s' WHERE id = %s'''%(code,id)
        cur.execute(update_table)
    conn.commit()
    cur.close()
    conn.close()
def create_code(id,length=15):
    code = hex(int(id))+'L'
    length_rdm = length - len(code)
    random_num = ''.join(random.sample(string.letters+string.digits,length_rdm))
    return code+random_num
if __name__ == '__main__':
    opt_mysql(300)


備註:spa

這個代碼的思路是借鑑的別人的,寫的不錯。code

http://linsir.org/post/Creat-the-unique-activation-code-with-python

相關文章
相關標籤/搜索