网上看到一个python练习题,要随机生成8位数的优惠券,并希望能保存到mysql数据库中。自己查资料写了下面的一段代码完成这个小作业
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author qingmiao
import
MySQLdb as mdb
import
sys
import
random,string
def
random_code(code_length,code_long):
i
=
1
result
=
[]
while
i<
=
code_length:
salt
=
''.join(random.sample(string.ascii_letters
+
string.digits, code_long))
result.append(salt)
i
=
i
+
1
return
result
def
save_to_mysql(num_list):
try
:
conn
=
mdb.connect(
"127.0.0.1"
,
"root"
,
"root"
,
"test"
)
cur
=
conn.cursor()
conn.select_db(
'test'
)
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()
if
__name__
=
=
'__main__'
:
code_num
=
random_code(
10
,
8
)
save_to_mysql(code_num)
|
最后去数据库看一下数据插入效果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
mysql>
select
* from active_code;
+-------------+
| active_code |
+-------------+
| frOkEoDA |
| zMabDOn0 |
| RjgKWCIb |
| G18spXBx |
| v8owJXyb |
| iwFOBZx9 |
| hA1MCrin |
| ErTNIxbO |
| x2A1boGL |
| beBLM3kI |
+-------------+
10 rows
in
set
(0.00 sec)
mysql>
|
本文转自 青苗飞扬 51CTO博客,原文链接:http://blog.51cto.com/qingmiao/2046112