Skip to content

Commit 7ca310b

Browse files
author
Will
authored
Create into_mysql.py
1 parent 78e157e commit 7ca310b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

will/0002/into_mysql.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# 第 0002 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
2+
'''
3+
相关模块/库 : pymysql
4+
1. http://www.runoob.com/python3/python3-mysql.html
5+
'''
6+
import random, string, time, math, uuid, pymysql
7+
8+
chars = string.ascii_letters + string.digits
9+
10+
def gen1():
11+
key = ''.join(random.sample(chars, 10))
12+
#key2 = ''.join(random.choice(chars) for i in range(10))
13+
return key
14+
15+
def gen2():
16+
key = math.modf(time.time())[0]
17+
return key
18+
19+
def gen3():
20+
return uuid.uuid4()
21+
22+
def dbp():
23+
db = pymysql.connect('localhost', 'root', '1213', 'python')
24+
cursor = db.cursor()
25+
cursor.execute("DROP TABLE IF EXISTS CODE")
26+
sql = """CREATE TABLE CODE (
27+
app_code CHAR(100) NOT NULL
28+
)"""
29+
cursor.execute(sql)
30+
return db, cursor
31+
32+
if __name__ == '__main__':
33+
db, cursor = dbp()
34+
for i in range(200):
35+
add_code = "INSERT INTO CODE(app_code) VALUES ('%s')" % gen2()
36+
# print(add_code)
37+
try:
38+
cursor.execute(add_code)
39+
db.commit()
40+
except:
41+
db.rollback()
42+
db.close()
43+
print('finish')
44+

0 commit comments

Comments
 (0)