Python 练习册 2-存储激活码到MySQL数据库
2016-04-14 17:38
651 查看
Python 练习册,每天一个小程序,原题来自Yixiaohan/show-me-the-code
我的代码仓库在Github
我的代码仓库在Github
目标
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 生成 200 个激活码(或者优惠券),并将激活码保存到 MySQL 关系型数据库中。解决方案
该题目采用 python 中的PyMySQL模块 来连接操作
MySQL数据库,代码如下:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 将0001题目中随机生成的验证码保存到MySQL数据库 import uuid import pymysql # 生成 num 个验证码,每个长度为length,可设置默认长度 def create_num(num, length=16): result = [] while num > 0: uuid_id = uuid.uuid4() # 删去字符串中的'-',取出前length 个字符 temp = str(uuid_id).replace('-', '')[:length] if temp not in result: result.append(temp) num -= 1 return result # 保存到MySQL数据库 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)
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法