网上看到一个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>
时间: 2024-12-28 20:43:49