Python Show-Me-the-Code 第 0002题
来源:互联网 发布:java架构师学习路线 编辑:程序博客网 时间:2024/05/22 17:44
第0002题:将0001题生成的200个激活码(或者优惠券)保存到MySQL关系型数据库中。
分析:这题需要使用mysql数据库.
1.首先要下载mysql
Window上安装Mysql相对来说会较为简单,你只需要载在MySQL 下载地址:http://www.mysql.com/downloads/中下载window版本的mysql安装包,并解压安装包。双击 setup.exe 文件,按照提示安装。最后验证是否安装正确:在cmd上输入mysqld.exe --console如果安装成功以上命令将输出一些mysql启动及InnoDB信息.
2.安装MySQL驱动
由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。目前,有两个MySQL驱动:
mysql-connector-python:是MySQL官方的纯Python驱动;
MySQL-python:是封装了MySQL C驱动的Python驱动。
3.在mysql中创建存储激活码的数据库和表
create database test;
create table t1( id int(4) not NULL primary key, code char(10));
4.编程
代码如下
import MySQLdbimport string,randomdef generateCode(n):r=[]s=string.digits+string.lettersfor i in range(200):t=''for j in range(n):t+=random.choice(s)r.append(t)return rHost='localhost'User='root'Password="123456"Port=3306DB='test'conn = MySQLdb.connect(user='root', passwd='123456', db='test', use_unicode=True)cur=conn.cursor()r=generateCode(8)for i in xrange(200):sql='INSERT INTO t1 (id,code) VALUES (%d,\'%s\');' % (i+1,r[i])cur.execute(sql)conn.commit()cur.close()conn.close()5.使用查询语句查看结果
select * from t1;
0 0
- Python Show-Me-the-Code 第 0002 题 MySQL操作
- Python Show-Me-the-Code 第 0002题
- python show-me-the-code 第0004
- Python Show-Me-the-Code 第 0003 题 Redis操作
- Python Show-Me-the-Code 第 0004 题 统计单词
- Python Show-Me-the-Code 第 0021题 密码加密
- Python Show-Me-the-Code 第 0001题
- python show-me-the-code 第0010题
- python show-me-the-code 第0011题
- python show-me-the-code 第0012题
- Python Show-Me-the-Code 第 0000 题 图片右上角加数字
- Python Show-Me-the-Code 第 0001 题 生成激活码
- Python Show-Me-the-Code 第 0005 题 批量图片处理
- Python Show-Me-the-Code 第 0006 题 最重要的词
- Python Show-Me-the-Code 第 0008 题 提取HTML正文内容
- Python Show-Me-the-Code 第 0009 题 提取网页中的超链接
- Python Show-Me-the-Code 第 0010 题 生成验证码图片
- Python Show-Me-the-Code 第 0011 题 过滤敏感词
- 十六进制数也可以这样输入。。
- [leetcode] 186. Reverse Words in a String II 解题报告
- selenium+python自动化中 读取文本属性值和读取文本值
- lua Date和Time
- nfs+ssh软连接无法实现免密码登陆
- Python Show-Me-the-Code 第 0002题
- linux下c/c++实例之七递归扫描目录下的文件
- 【C#】 关于属性
- 国际会议级别
- hdu 1950 Bridging signals 最长上升子序列
- bootstrap-datetimepicker日期时间选择器使用文档
- 链表基本操作
- 对照Java学习Swift--基本运算符
- 一个及格的java程序员应该有这个能力