Skip to content

Commit 02da423

Browse files
committed
Add solution of 0002
1 parent 82da89b commit 02da423

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
# Author: illuz <iilluzen[at]gmail.com>
4+
# File: create_a_table_and_put_keys.py
5+
# Create Date: 2015-02-09 12:12:43
6+
# Usage: create_a_table_and_put_keys.py
7+
# Descripton: create a table in mysql and put keys into it
8+
9+
"""
10+
第 0002 题:
11+
将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
12+
"""
13+
14+
from uuid import uuid4
15+
import MySQLdb as mdb
16+
17+
18+
def generate_key(num):
19+
key_list = [str(uuid4()) for i in range(num)]
20+
return key_list
21+
22+
23+
def create_a_table_and_put_keys(key_list):
24+
with mdb.connect('localhost', 'test', '123', 'testdb') as cur:
25+
26+
# create table
27+
cur.execute("DROP TABLE IF EXISTS rkeys")
28+
cur.execute("CREATE TABLE rkeys(\
29+
key_value CHAR(40) NOT NULL\
30+
)")
31+
32+
# insert data
33+
# I want to use executemany, but there is a library bug...
34+
# It seems that executemany cannot match single-string list
35+
# cur.executemany("INSERT INTO rkeys VALUES(%s)", key_list)
36+
for i in key_list:
37+
cur.execute("INSERT INTO rkeys(key_value)\
38+
VALUES('%s')" % i)
39+
40+
41+
def main():
42+
create_a_table_and_put_keys(generate_key(200))
43+
44+
45+
if __name__ == '__main__':
46+
main()

0 commit comments

Comments
 (0)