========================
题目
将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
分析
这里考察的是对数据库的基本操作,这里使用PyMySQL库。
pip install pymysql
准备
- 目前Linux 的Mysql软件为MariaDB,它是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可。以Arch Linux下安装MariaDB数据库为例:
1 2 3 4
| sudo pacman -S mariadb sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql sudo systemctl start mariadb mysql -u root mysql
|
关于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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import uuid def Generate_Code(counts,length=20): key_list = []
for i in range(counts): key = str(uuid.uuid4())[:length] if key not in key_list: key_list.append(key)
return key_list
import pymysql
if __name__ == "__main__": key = Generate_Code(200,20)
conn = pymysql.connect( host = "127.0.0.1", user = "root", password = "", database = "test", charset = 'utf8', cursorclass=pymysql.cursors.DictCursor) try: with conn.cursor() as cursor: cursor.execute("DROP TABLE IF EXISTS code") sql = """CREATE TABLE code( id INT UNSIGNED AUTO_INCREMENT, code VARCHAR(32) NOT NULL, PRIMARY KEY(id) )ENGINE=InnoDB DEFAULT CHARSET=utf8; """ cursor.execute(sql)
cursor.executemany("INSERT INTO code(code) VALUES(%s);",key) conn.commit()
with conn.cursor() as cursor: cursor.execute("SELECT * FROM code;") print( cursor.fetchall() )
finally: conn.close()
|
扩展
日常写个小玩具可以用更轻量级的SQLite3,它是一个小巧的储存在本地的数据库。
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 36 37 38 39 40 41 42 43 44
| import uuid def Generate_Code(counts,length=20): key_list = []
for i in range(counts): key = str(uuid.uuid4())[:length] if key not in key_list: key_list.append( (key,))
return key_list key = Generate_Code(200,20)
import sqlite3
conn = sqlite3.connect("test.db") c = conn.cursor()
sql = """CREATE TABLE KEY( ID INTEGER PRIMARY KEY autoincrement, CODE TEXT NOT NULL );""" c.execute(sql)
c.executemany("INSERT INTO KEY VALUES(NULL,?);",key)
conn.commit()
c.execute("SELECT * FROM KEY;") print( c.fetchall() )
c.close() conn.close()
|
参考