您的位置:首页 > 编程语言 > Python开发

Python 练习册,每天一个小程序 -- 0002题

2015-12-25 17:02 751 查看
有段时间没写博客了,继续写练习题
第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

分析问题:
由于是要把数据保存到mysql中,这里就需要用到MySQLdb模块,并且先生成再存入,
注意:
1 这里操作MySQL的时候,先写入一条,获得id,然后再更新该条记录。
2 创建的验证码的格式为---'16进制的sql_id' + 'L' + 随机码
上代码:
#!/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)


备注:
这个代码的思路是借鉴的别人的,写的不错。 http://linsir.org/post/Creat-the-unique-activation-code-with-python
本文出自 “一个奋斗的小运维” 博客,请务必保留此出处http://yucanghai.blog.51cto.com/5260262/1728344
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: