第0002题:将0001题生成的200个激活码(或者优惠券)保存到MySQL关系型数据库中。
如果第0001题顺利解决,然后加上其他队MySQL的文章介绍,应该不难解决这一题了。
思路如下:
- 首先拿到200个激活码
- 然后连接数据库,连接数据库,建表,插入数据
- 验证结果,可以把插入的数据打印出来
代码如下
#! /usr/bin/env python
#coding=utf-8
import uuid
import MySQLdb as mdb
import sys
def create_code(num, length):
result = []
while 1:
uuid_id = uuid.uuid1()
temp = str(uuid_id).replace("-", '')[:length]
if temp not in result:
result.append(temp)
if len(result) == num:
break
return result
def save_to_mysql(num_list):
try:
conn = mdb.connect("localhost", "testuser", "test623", "testdb")
cur = conn.cursor()
# sql_to_create_database = 'create database if not exists testdb'
# cur.execute(sql_to_create_database)
conn.select_db('testdb')
sql_to_drop_table = 'drop table if exists active_code'
cur.execute(sql_to_drop_table)
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()
def fetch_all_results(db="testdb"):
try:
conn = mdb.connect("localhost", "testuser", "test623", "testdb")
with conn:
cur = conn.cursor()
sql_to_retrieve_all = "select * from active_code"
cur.execute(sql_to_retrieve_all)
rows = cur.fetchall()
for row in rows:
print row
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 = create_code(200, 20)
save_to_mysql(code_num)
fetch_all_results()
网友评论