MySQL
- Python DB-API
- Python操作mysql
- MySQL事务
0x01 Python DB-API
- 使用流程
* 引入API模块
* 获取与数据连接
* 执行SQL语句和存储过程
* 关闭数据库连接
0x02 Python操作mysql
- 安装包
* MySQLdb用于Python链接MySQl数据库接口。实现Python数据库API
* 基于MySQL C API上建立连接
* Example:
```
yum install -y python-devel
yum install -y mysql-devel
yum install -y gcc
```
- pip 安装 MySQLdb
* MySQLdb只适用python2
* python3之后不支持MySQLdb,使用pymysql包
* python3使用pymysql
* Example: Python2
```
pip search mysqldb
```
* Example: Python3
```
pip search pymysql
pip install pymysql
```
* Example: Python操作mysql完整过程
```
# 创建链接
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = '123456',
db = 'Database'
)
# 创建游标
cursor = conn.cursor()
# 执行SQL,并返回值
print_row = cursor.execute('update hosts set host = "192.168.10.111" where id > %s', (1,))
# 按1一条一条取数据
print_input = cursor.fetchone()
print(print_input)
# 执行SQL,并返回值
print_rw = cursor.executemany('insert into hosts(host, color, id) values(%s, %s)', [('192.168.10.120', 1), ('192.168.10.121'), 2])
# 提交, 不然无法保持新建或修改
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
```
* Example: Python操作示例
```
import pymysql
data = [
("N1", "2018-05-09", 'M'),
("N1", "2018-05-09", 'G'),
("N1", "2018-05-09", 'F'),
]
cursor.executemany("insert into student (name, register, gender) value (%s, %s, %s)", data)
conn.commit()
```
- SQLAchemy
* 是Python编程语言下的ORM框架,建立在数据库API之上
* 使用关系对象映射数据库操作
* 即:将对象转换成SQL, 在使用数据API执行SQL并获取执行结果
- ORM介绍
* 对象映射关系
* 通过ORM将编程语言的对象模型和数据的关系模型建立映射关系
* 避免直接使用SQL语言
- ORM优点
* 隐藏数据库访问细节,"封闭性"数据库交互,与数据库交互简单,不需考利SQL语句
* 构造固化数据结构变得简单易行
- sqlalchemy安装
* 框架SQLAlchemy
* 安装
pip install SQLAlchemy pip install pymysql
* 官方参考文档
http://docs.sqlalchemy.org/en/latest/intro.html
- 基本使用
* 基本方式创建表
create table name ( id integer not null auto_increment, name varchar(40), password varchar(64), primary key (id) )
* 不同数据库API调用方式
```
# MySQL-Python
mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
# pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
# MySQL-Connector
mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
# cx_Oracle
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
# mssql
eng = create_engine("mssql+pymssql://mydsn", legacy_schema_aliasing=True)
```
* 基于ORM方式创建表
```
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
engine = create_engine("mysql + pymysql://root:123456@127.168.10.120/test", encoding= "utf-8", echo = True)
# 生成orm基类
Base = daclarative_base()
class User(Base):
__tablename__ = 'name' # 表名
id = Column(Integer, primary_key=True)
name = Column(String(32))
password = Column(String(64))
# 创建表结构
Base.metadata.create_all(engine)
```
0x03 MySQL部分
show databases; # 查看库
use test; # 使用test库
show tables G; # 查看表
select * from test; # 查看test表数据
select * from testG; # 以树形形式显示单条数据
show create table test; # 查看建表语句
select user(); # 查看当前用户
select database(); # 查看当前库
show mame from test; # 显示数据表属性, 属性类型, 主键等信息
create database test; # 创建库
show create database test; # 查看创建库信息
show index from test; # 显示数据表详细索引信息
create table (id int, name char(12), adress char(20))
commit; # 提交
rollback; # 回滚至上一次提交的位置
show variables like "%auto%" # 显示是否自动提交, on开启 off关闭
insert into test (time, name, id) values ('20180506', 'anChow', '25') # 插入字段
desc test; # 查看表结构
grant all privileges on *.* to 'anChow'@'%' identified by '123456' with grant option; # 授权超级用户
show grants for anChwo; # 查看授权信息
show full processlist # 查看队列
show processlist # 查看队列
flush privliges; # 刷新内存
create table student( # 创建student表
id int not null auto_increment, # 字段 id 整型 不能为空, 自增列
name char(40) not null, # 字段 name 字符型 不能为空
age int not null, # 整型
register date, # 日期型
primary key (id) # 主键为id列
);
insert into student (name, age register) values ('anChwo', 20, '2018-05-08 10:20:30')
- Example: mysql操作之select查询
select * from student; # 查询表所有内容
select * from student limit 2; #
select * from student limit 2 offset 1; # 忽略第一条,从第二条开始
select * from student where age > 18; # 通过where判断
select * from student where id > 3 and age > 18; # 多条件判断
select * from student name like 'an%'; # 模糊查询
select * from student name like binary '%C%'; #只匹配大写
# ASC 降序 DESC 升序, 默认按升序
select * from student where name like binary anC% order by age desc;
- Example: mysql操作之group by
# 查询age字段,统计出现的次数
select age, count(*) from student group by age;
#
select *, count(*) from student group by name having count(*)>1;
# 求年龄总和
select age, sum(age) from student group by age;
# 通过coalesce设置取代null的名称
select coalesec(name, '总数'), sum(age) as Total_Age frp, stidemt group by age with rollup;
- Example: mysql操作之update更新
# 更新id为2的name字段
update student set name='Robin.anChow', age = 18 where id = 2;
# 更新日期
update student set register='2018-02-24' where id = 5;
# 增加字段
alter table student add sex enum('M', 'F');
# Modify实现修改字段
alter table student modify sex enum('F', 'M', 'X') not null;
# Change实现修改字段
alter table student change sex Man char(32) not null default "x";
# 设置默认值
alter table student modify sex not null default 'Man';
alter table student rename to newstudent;
delete from student where id = 4;
select * from student inner join test on student.id = test.id;
#
select * from student left join test on student.id = test.id;
#
select * from student right join test on student.id = test.id;
# 并集
select * from student left join test on student.id = test.id union select * from student right join test on student.id = test.id;
#
select student.*, test.* from student, test where student.id = test.id;
- 注意点
* 只有Innodb数据库引擎支持数据库或表的事务
* 事务处理可以用来维护数据库完整性,保证批量SQL语句完整执行或全部不执行
* 用来管理insert, update, delete语句
- 满足条件(ACID)
* Atomicity --- 原子性
* Consistency --- 稳定性
* Isolation --- 隔离性
* Durability --- 可靠性
# 开启事务
mysql> begin;
# 插入数据
mysql> insert into student (name) valuess(aaa);
# 提交事务 ---> 没问题
mysql> commit;
# 回滚事务 ---> 有问题
mysql> rollback;
- 索引
* 特点
--- 高效运行,提高检索速度
* 索引分类
--- 单列索引: 只包含单列
--- 组合索引: 可包含多列
* 含义
--- 一张表,保存主键与索引字段。指向实体表记录
* 缺点
--- 提高查询速度, 同时也降低更新表速度
--- 更新表时, 不仅要保持源数据, 还要保存索引文件
--- 会占用磁盘空间
create index indexname on student(name(32));
create table student(
id init not null,
name varchar(32) not null,
index [indexname] (name(32))
);
drop index [indexname] on student;
mysql> show index from studentG
- 唯一索引
* 索引值必须唯一, 允许有空值
* 若是组合索引, 则列值组合必须唯一
0x04