1. 程式人生 > >Python隨機生成指定長度字符串並保存到mysql中

Python隨機生成指定長度字符串並保存到mysql中

python random

網上看到一個python練習題,要隨機生成8位數的優惠券,並希望能保存到mysql數據庫中。自己查資料寫了下面的一段代碼完成這個小作業
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author qingmiao
import MySQLdb as mdb
import sys
import random,string

def random_code(code_length,code_long):
    i=1
    result = []
    while i<=code_length:
        salt = ''.join(random.sample(string.ascii_letters + string.digits, code_long))
        result.append(salt)
        i=i+1
    return result

def save_to_mysql(num_list):
    try:
        conn = mdb.connect("127.0.0.1", "root", "root", "test")
        cur = conn.cursor()
        conn.select_db('test')
        sql_to_create_table = 'create table if not exists active_code(active_code char(32))'
        cur.execute(sql_to_create_table)
        cur.executemany('insert into active_code values(%s)', num_list)
        conn.commit()
    except mdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)
    finally:
        if conn:
            conn.close()

if __name__ == '__main__':
    code_num = random_code(10,8)
    save_to_mysql(code_num)

最後去數據庫看一下數據插入效果:

mysql> select * from active_code;
+-------------+
| active_code |
+-------------+
| frOkEoDA    |
| zMabDOn0    |
| RjgKWCIb    |
| G18spXBx    |
| v8owJXyb    |
| iwFOBZx9    |
| hA1MCrin    |
| ErTNIxbO    |
| x2A1boGL    |
| beBLM3kI    |
+-------------+
10 rows in set (0.00 sec)
mysql>


Python隨機生成指定長度字符串並保存到mysql中