第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 MySQLdb
import string,random
def generateCode(n):
r=[]
s=string.digits+string.letters
for i in range(200):
t=''
for j in range(n):
t+=random.choice(s)
r.append(t)
return r
Host='localhost'
User='root'
Password="123456"
Port=3306
DB='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;