第1.3题:将 200 个激活码保存到 MySQL

题目来自:Python 练习册,今天做的是第三题,使用 Python 将激活码保存到 MySQL。


准备姿势

安装Mysql

如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可。

Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的linux 仓库中都会有mysql ,我们只需要通过一个命令就可以下载安装:

Ubuntu\deepin

1
2
sudo apt-get install mysql-server 
sudo apt-get install mysql-client

centOS/redhat

1
yum install mysql

安装MySQL-python

要想使python可以操作mysql 就需要MySQL-python驱动,它是python 操作mysql必不可少的模块。

下载地址:https://pypi.python.org/pypi/MySQL-python/

下载MySQL-python-1.2.5.zip 文件之后直接解压。进入MySQL-python-1.2.5目录:

1
python setup.py install

可能会提示缺少“error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat). Get it from http://aka.ms/vcpython27
这个地方查找了很多资料,有的说要修改注册表,有的说要改VS2015的配置。简直一派胡言,I am angry。直接按照要求,在这个http://aka.ms/vcpython27下载安装就可以了。

Microsoft Visual C++ Compiler for Python 2.7

测试

输入

1
import MySQLdb

或者
1
import mysql

如果不报错,那么就安装成功了。


mysql 的基本操作

  • 启动mysql
    1
    mysql -u root -p
  • 查看当前所有的数据库
    1
    show databases;  
  • 新建数据库表
    1
    create database if not exists test; 
  • 使用某表
    1
    use test;
  • 添加数据
    1
    insert into user values('Alen','7875');
  • 查看数据
    1
    select * from student
  • 删除数据
    1
    delete from user where name = 'Jack';
  • 删除table
    1
    drop table if exists student
  • 删除database
    1
    drop database if exists test
  • mysql卡死怎么办
    查看目前连接情况:
    1
    show processlist;
    卡死
    发现多个线程数据处理间出现了死锁,也没什么好的办法,kill掉就可以了。
    1
    kill 65;
    然后就可以继续使用了。

python 操作mysql基本语法

  • 建立数据库连接
    注意,这个地方的test表要存在,否则无法连接
    1
    2
    3
    4
    5
    6
    7
    8
    9
    import MySQLdb
    conn=MySQLdb.connect(
    host='localhost',
    port = 3306, #默认3306端口,不写也可以
    user='root',
    passwd='123456',
    db ='test',
    )
    cur = conn.cursor()

cursor 是游标, 通过获取到的数据库连接conn下的cursor()方法来创建游标。
其中,第二行代码可以缩写为:

1
connect('localhost', 'root', '123456', 'test')

  • 创建数据表
    1
    2
    cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") 
    #通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。
  • 插入一条数据
    1
    cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
  • 修改查询条件的数据
    1
    cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
  • 删除查询条件的数据
    1
    cur.execute("delete from student where age='9'")
  • 关闭游标
    1
    cur.close() 
  • 提交数据
    向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入。
    1
    conn.commit()
  • 关闭数据库连接
    1
    conn.close()

    打印表中所有数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()

#获得表中有多少条数据
aa=cur.execute("select * from student")
print aa

#打印表中的多少数据
info = cur.fetchmany(aa)
for ii in info:
print ii
cur.close()
conn.commit()
conn.close()

插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()

#一次插入多条记录
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
('3','Tom','1 year 1 class','6'),
('3','Jack','2 year 1 class','7'),
('3','Yaheng','2 year 2 class','7'),
])

cur.close()
conn.commit()
conn.close()

以上两段代码参考 虫师的博客


正式代码

经过以上铺垫之后,就可以写出满足要求的代码了。

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
from uuid import uuid4
import MySQLdb,random, string
chars = string.digits + string.letters

def uuidkey(num):# 使用uuid方法得到随机值
id_list = [str(uuid4()) for i in range(num)]
return id_list

def randomkey(num):# 使用random随机取数据值
id_list = ["".join(random.sample(chars, 20)) for i in range(num)]
return id_list

def create_table_put_keys(id_list,table):#将获得的随机值存入mysql
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='lyyc12345',
db ='test',
)
cur = conn.cursor()
cur.execute("drop table if exists %s" % table) #若存在table表则删除
cur.execute("create table %s(id int, coupon char(40))" % table) #创建数据表
temp = 1
for i in id_list: #将id_list里边的数据插入到mysql中
cur.execute("insert into %s values('%d','%s')" %(table,temp,i))
temp=temp+1
cur.close() #关闭游标
conn.commit() #提交数据
conn.close() #关闭数据库连接

def main():
create_table_put_keys(uuidkey(200),'uuidtable')
create_table_put_keys(randomkey(200),'randomtable')

if __name__ == '__main__':
main()

总结

  • python 中 % 的使用:cur.execute("insert into %s values('%d','%s')" %(table,temp,i)),前后两部分用%相隔
  • 提交数据conn.commit(),否则数据将不会保存。

第1.3题:将 200 个激活码保存到 MySQL

https://iii.run/archives/c596ea22b542.html

作者

mmmwhy

发布于

2017-02-10

更新于

2022-10-08

许可协议

评论