Python之数据库

Python之数据库:

        1. Mysql

        2. pymysql

        3. SQLAlchemy

 

Mysql

一、概述

什么是数据库 ?
 答:数据的仓库,如:在ATM的示例中我们创建了一个 db 目录,称其为数据库

什么是 MySQL、Oracle、SQLite、Access、MS SQL Server等 ?
 答:他们均是一个软件,都有两个主要的功能:

  • a. 将数据保存到文件或内存
  • b. 接收特定的命令,然后对文件进行相应的操作

    PS:如果有了以上软件,无须自己再去创建文件和文件夹,而是直接传递 命令 给上述软件,让其来进行文件操作,他们统称为数据库管理系统(DBMS,Database Management System)

什么是SQL ?
 答:上述提到MySQL等软件可以接受命令,并做出相应的操作,由于命令中可以包含删除文件、获取文件内容等众多操作,对于编写的命令就是是SQL语句。SQL􏰉􏵮􏵯􏰟,是􏵱􏰚􏵲􏵳􏵴􏰇􏰈􏵱􏰚􏵲􏵳􏵴􏰇􏰈结构化语言(Structured Query Language􏰕􏰐􏵵􏰯)的缩写,SQL􏰜􏰖􏰩􏰽􏵶􏱥􏲲􏰄􏰫􏰬􏰭􏵁􏵷􏰐􏰇􏰈是一种专门用来与数据库通信的语言。

二、下载安装

MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下公司。MySQL 最流行的关系型数据库管理系统,在 WEB 应用方面MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。

想要使用MySQL来存储并操作数据,则需要做几件事情:
  a. 安装MySQL服务端
  b. 安装MySQL客户端
  b. 【客户端】连接【服务端】
  c. 【客户端】发送命令给【服务端MySQL】服务的接受命令并执行相应操作(增删改查等)

1 下载
2         http://dev.mysql.com/downloads/mysql/
3 安装
4         windows:
5             点点点
6         Linux:
7             yum install mysql-server
8         Mac:
9             点点点

三、数据库操作

1、显示数据

1 SHOW DATABASES;

默认数据库:
  mysql - 用户权限相关数据
  test - 用于用户测试数据
  information_schema - MySQL本身架构相关数据

2、使用数据库

1 USE db_name;

3、显示所有表

1 SHOW TABLES;

4、用户授权

用户管理:

 1 创建用户
 2     create user '用户名'@'IP地址' identified by '密码';
 3 删除用户
 4     drop user '用户名'@'IP地址';
 5 修改用户
 6     rename user '用户名'@'IP地址'; to '新用户名'@'IP地址';;
 7 修改密码
 8     set password for '用户名'@'IP地址' = Password('新密码')
 9  
10 PS:用户权限相关数据保存在mysql数据库的user表中,所以也可以直接对其进行操作(不建议)

授权管理:

1 show grants for '用户'@'IP地址'                  -- 查看权限
2 grant  权限 on 数据库.表 to   '用户'@'IP地址'      -- 授权
3 revoke 权限 on 数据库.表 from '用户'@'IP地址'      -- 取消权限
 1 all privileges  除grant外的所有权限
 2             select          仅查权限
 3             select,insert   查和插入权限
 4             ...
 5             usage                   无访问权限
 6             alter                   使用alter table
 7             alter routine           使用alter procedure和drop procedure
 8             create                  使用create table
 9             create routine          使用create procedure
10             create temporary tables 使用create temporary tables
11             create user             使用create user、drop user、rename user和revoke  all privileges
12             create view             使用create view
13             delete                  使用delete
14             drop                    使用drop table
15             execute                 使用call和存储过程
16             file                    使用select into outfile 和 load data infile
17             grant option            使用grant 和 revoke
18             index                   使用index
19             insert                  使用insert
20             lock tables             使用lock table
21             process                 使用show full processlist
22             select                  使用select
23             show databases          使用show databases
24             show view               使用show view
25             update                  使用update
26             reload                  使用flush
27             shutdown                使用mysqladmin shutdown(关闭MySQL)
28             super                   􏱂􏰈使用change master、kill、logs、purge、master和set global。还允许mysqladmin􏵗􏵘􏲊􏲋调试登陆
29             replication client      服务器位置的访问
30             replication slave       由复制从属使用
31 
32 对于权限
对于权限
1  对于目标数据库以及内部其他:
2             数据库名.*           数据库中的所有
3             数据库名.表          指定数据库中的某张表
4             数据库名.存储过程     指定数据库中的存储过程
5             *.*                所有数据库
对于数据库
1 用户名@IP地址         用户只能在改IP下才能访问
2             用户名@192.168.1.%   用户只能在改IP段下才能访问(通配符%表示任意)
3             用户名@%             用户可以再任意IP下访问(默认IP地址为%)
对于用户和IP
1 grant all privileges on db1.tb1 TO '用户名'@'IP'
2 
3             grant select on db1.* TO '用户名'@'IP'
4 
5             grant select,insert on *.* TO '用户名'@'IP'
6 
7             revoke select on db1.tb1 from '用户名'@'IP'
示例

四、表操作

1、创建表

1 create table 表名(
2     列名  类型  是否可以为空,
3     列名  类型  是否可以为空
4 )
1  是否可空,null表示空,非字符串
2             not null    - 不可空
3             null        - 可空
1 默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
2             create table tb1(
3                 nid int not null defalut 2,
4                 num int not null
5             )
 1 自增,如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列)
 2             create table tb1(
 3                 nid int not null auto_increment primary key,
 4                 num int null
 5             )
 6  7             create table tb1(
 8                 nid int not null auto_increment,
 9                 num int null,
10                 index(nid)
11             )
12             注意:1、对于自增列,必须是索引(含主键)。
13                  2、对于自增可以设置步长和起始值
14                      show session variables like 'auto_inc%';
15                      set session auto_increment_increment=2;
16                      set session auto_increment_offset=10;
17 
18                      shwo global  variables like 'auto_inc%';
19                      set global auto_increment_increment=2;
20                      set global auto_increment_offset=10;
 1 主键,一种特殊的唯一索引,不允许有空值,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。
 2             create table tb1(
 3                 nid int not null auto_increment primary key,
 4                 num int null
 5             )
 6  7             create table tb1(
 8                 nid int not null,
 9                 num int not null,
10                 primary key(nid,num)
11             )
12 
13 主键
 1 外键,一个特殊的索引,只能是指定内容
 2             creat table color(
 3                 nid int not null primary key,
 4                 name char(16) not null
 5             )
 6 
 7             create table fruit(
 8                 nid int not null primary key,
 9                 smt char(32) null ,
10                 color_id int not null,
11                 constraint fk_cc foreign key (color_id) references color(nid)
12             )
13 
14 外键

2、删除表

1 drop table 表名

3、清空表

1 delete from 表名
2 truncate table 表名

4、修改表

 1 添加列:alter table 表名 add 列名 类型
 2 删除列:alter table 表名 drop column 列名
 3 修改列:
 4         alter table 表名 modify column 列名 类型;  -- 类型
 5         alter table 表名 change 原列名 新列名 类型; -- 列名,类型
 6  
 7 添加主键:
 8         alter table 表名 add primary key(列名);
 9 删除主键:
10         alter table 表名 drop primary key;
11         alter table 表名  modify  列名 int, drop primary key;
12  
13 添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
14 删除外键:alter table 表名 drop foreign key 外键名称
15  
16 修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
17 删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

5、基本数据类型

MySQL的数据类型大致分为:数值、时间和字符串

http://www.runoob.com/mysql/mysql-data-types.html

 

五、基本操作

1、增

1 insert into 表 (列名,列名...) values (值,值,值...)
2         insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
3         insert into 表 (列名,列名...) select (列名,列名...) from

2、删

1 delete from2         delete from 表 where id=1 and name='alex'

3、改

1 update 表 set name = 'alex' where id>1

4、查

1 select * from2         select * from 表 where id > 1
3         select nid,name,gender as gg from 表 where id > 1

5、其他

 1 1、条件
 2         select * from 表 where id > 1 and name != 'alex' and num = 12;
 3 
 4         select * from 表 where id between 5 and 16;
 5 
 6         select * from 表 where id in (11,22,33)
 7         select * from 表 where id not in (11,22,33)
 8         select * from 表 where id in (select nid from 表)
 9 
10     2、通配符
11         select * from 表 where name like 'ale%'  - ale开头的所有(多个字符串)
12         select * from 表 where name like 'ale_'  - ale开头的所有(一个字符)
13 
14     3、限制
15         select * from 表 limit 5;            - 前5行
16         select * from 表 limit 4,5;          - 从第4行开始的5行
17         select * from 表 limit 5 offset 4    - 从第4行开始的5行
18 
19     4、排序
20         select * from 表 order by 列 asc              - 根据 “列” 从小到大排列
21         select * from 表 order by 列 desc             - 根据 “列” 从大到小排列
22         select * from 表 order by 列1 desc,列2 asc    - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
23 
24     5、分组
25         select num from 表 group by num
26         select num,nid from 表 group by num,nid
27         select num,nid from 表  where nid > 10 group by num,nid order nid desc
28         select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
29 
30         select num from 表 group by num having max(id) > 10
31 
32         特别的:group by 必须在where之后,order by之前
33 
34     6、连表
35         无对应关系则不显示
36         select A.num, A.name, B.name
37         from A,B
38         Where A.nid = B.nid
39 
40         无对应关系则不显示
41         select A.num, A.name, B.name
42         from A inner join B
43         on A.nid = B.nid
44 
45         A表所有显示,如果B中无对应关系,则值为null
46         select A.num, A.name, B.name
47         from A left join B
48         on A.nid = B.nid
49 
50         B表所有显示,如果B中无对应关系,则值为null
51         select A.num, A.name, B.name
52         from A right join B
53         on A.nid = B.nid
54 
55     7、组合
56         组合,自动处理重合
57         select nickname
58         from A
59         union
60         select name
61         from B
62 
63         组合,不处理重合
64         select nickname
65         from A
66         union all
67         select name
68         from B
View Code

pymsql

  pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

 

一、下载安装:

1 pip3 install pymysql

二、使用

1、执行SQL

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4  
 5 # 创建连接
 6 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 7 # 创建游标
 8 cursor = conn.cursor()
 9  
10 # 执行SQL,并返回收影响行数
11 effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
12  
13 # 执行SQL,并返回受影响行数
14 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
15  
16 # 执行SQL,并返回受影响行数
17 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
18  
19  
20 # 提交,不然无法保存新建或者修改的数据
21 conn.commit()
22  
23 # 关闭游标
24 cursor.close()
25 # 关闭连接
26 conn.close()

2、获取新创建数据自增ID

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4  
 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 6 cursor = conn.cursor()
 7 cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
 8 conn.commit()
 9 cursor.close()
10 conn.close()
11  
12 # 获取最新自增ID
13 new_id = cursor.lastrowid

3、获取查询数据

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4  
 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 6 cursor = conn.cursor()
 7 cursor.execute("select * from hosts")
 8  
 9 # 获取第一行数据
10 row_1 = cursor.fetchone()
11  
12 # 获取前n行数据
13 # row_2 = cursor.fetchmany(3)
14 # 获取所有数据
15 # row_3 = cursor.fetchall()
16  
17 conn.commit()
18 cursor.close()
19 conn.close()

注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

  • cursor.scroll(1,mode='relative')  # 相对当前位置移动
  • cursor.scroll(2,mode='absolute') # 相对绝对位置移动

4、fetch数据类型

  关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import pymysql
 4  
 5 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
 6  
 7 # 游标设置为字典类型
 8 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
 9 r = cursor.execute("call p1()")
10  
11 result = cursor.fetchone()
12  
13 conn.commit()
14 cursor.close()
15 conn.close()

SQLAchemy

SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:

 1 MySQL-Python
 2     mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
 3   
 4 pymysql
 5     mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
 6   
 7 MySQL-Connector
 8     mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
 9   
10 cx_Oracle
11     oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
12   
13 更多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html

一、底层处理

使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from sqlalchemy import create_engine
 4  
 5  
 6 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
 7  
 8 # 执行SQL
 9 # cur = engine.execute(
10 #     "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)"
11 # )
12  
13 # 新插入行自增ID
14 # cur.lastrowid
15  
16 # 执行SQL
17 # cur = engine.execute(
18 #     "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),]
19 # )
20  
21  
22 # 执行SQL
23 # cur = engine.execute(
24 #     "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",
25 #     host='1.1.1.99', color_id=3
26 # )
27  
28 # 执行SQL
29 # cur = engine.execute('select * from hosts')
30 # 获取第一行数据
31 # cur.fetchone()
32 # 获取第n行数据
33 # cur.fetchmany(3)
34 # 获取所有数据
35 # cur.fetchall()

二、ORM功能使用

使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。

1、创建表

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from sqlalchemy.ext.declarative import declarative_base
 4 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 5 from sqlalchemy.orm import sessionmaker, relationship
 6 from sqlalchemy import create_engine
 7 
 8 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
 9 
10 Base = declarative_base()
11 
12 # 创建单表
13 class Users(Base):
14     __tablename__ = 'users'
15     id = Column(Integer, primary_key=True)
16     name = Column(String(32))
17     extra = Column(String(16))
18 
19     __table_args__ = (
20     UniqueConstraint('id', 'name', name='uix_id_name'),
21         Index('ix_id_name', 'name', 'extra'),
22     )
23 
24 
25 # 一对多
26 class Favor(Base):
27     __tablename__ = 'favor'
28     nid = Column(Integer, primary_key=True)
29     caption = Column(String(50), default='red', unique=True)
30 
31 
32 class Person(Base):
33     __tablename__ = 'person'
34     nid = Column(Integer, primary_key=True)
35     name = Column(String(32), index=True, nullable=True)
36     favor_id = Column(Integer, ForeignKey("favor.nid"))
37 
38 
39 # 多对多
40 class Group(Base):
41     __tablename__ = 'group'
42     id = Column(Integer, primary_key=True)
43     name = Column(String(64), unique=True, nullable=False)
44     port = Column(Integer, default=22)
45 
46 
47 class Server(Base):
48     __tablename__ = 'server'
49 
50     id = Column(Integer, primary_key=True, autoincrement=True)
51     hostname = Column(String(64), unique=True, nullable=False)
52 
53 
54 class ServerToGroup(Base):
55     __tablename__ = 'servertogroup'
56     nid = Column(Integer, primary_key=True, autoincrement=True)
57     server_id = Column(Integer, ForeignKey('server.id'))
58     group_id = Column(Integer, ForeignKey('group.id'))
59 
60 
61 def init_db():
62     Base.metadata.create_all(engine)
63 
64 
65 def drop_db():
66     Base.metadata.drop_all(engine)

ForeignKeyConstraint(['other_id'], ['othertable.other_id']),

2、操作表

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from sqlalchemy.ext.declarative import declarative_base
 4 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
 5 from sqlalchemy.orm import sessionmaker, relationship
 6 from sqlalchemy import create_engine
 7 
 8 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
 9 
10 Base = declarative_base()
11 
12 # 创建单表
13 class Users(Base):
14     __tablename__ = 'users'
15     id = Column(Integer, primary_key=True)
16     name = Column(String(32))
17     extra = Column(String(16))
18 
19     __table_args__ = (
20     UniqueConstraint('id', 'name', name='uix_id_name'),
21         Index('ix_id_name', 'name', 'extra'),
22     )
23 
24     def __repr__(self):
25         return "%s-%s" %(self.id, self.name)
26 
27 # 一对多
28 class Favor(Base):
29     __tablename__ = 'favor'
30     nid = Column(Integer, primary_key=True)
31     caption = Column(String(50), default='red', unique=True)
32 
33     def __repr__(self):
34         return "%s-%s" %(self.nid, self.caption)
35 
36 class Person(Base):
37     __tablename__ = 'person'
38     nid = Column(Integer, primary_key=True)
39     name = Column(String(32), index=True, nullable=True)
40     favor_id = Column(Integer, ForeignKey("favor.nid"))
41     # 与生成表结构无关,仅用于查询方便
42     favor = relationship("Favor", backref='pers')
43 
44 # 多对多
45 class ServerToGroup(Base):
46     __tablename__ = 'servertogroup'
47     nid = Column(Integer, primary_key=True, autoincrement=True)
48     server_id = Column(Integer, ForeignKey('server.id'))
49     group_id = Column(Integer, ForeignKey('group.id'))
50     group = relationship("Group", backref='s2g')
51     server = relationship("Server", backref='s2g')
52 
53 class Group(Base):
54     __tablename__ = 'group'
55     id = Column(Integer, primary_key=True)
56     name = Column(String(64), unique=True, nullable=False)
57     port = Column(Integer, default=22)
58     # group = relationship('Group',secondary=ServerToGroup,backref='host_list')
59 
60 
61 class Server(Base):
62     __tablename__ = 'server'
63 
64     id = Column(Integer, primary_key=True, autoincrement=True)
65     hostname = Column(String(64), unique=True, nullable=False)
66 
67 
68 
69 
70 def init_db():
71     Base.metadata.create_all(engine)
72 
73 
74 def drop_db():
75     Base.metadata.drop_all(engine)
76 
77 
78 Session = sessionmaker(bind=engine)
79 session = Session()
80 
81 表结构+连接数据库
表结构+连接数据库
  •   
1 obj = Users(name="alex0", extra='sb')
2 session.add(obj)
3 session.add_all([
4     Users(name="alex1", extra='sb'),
5     Users(name="alex2", extra='sb'),
6 ])
7 session.commit()
View Code
1 session.query(Users).filter(Users.id > 2).delete()
2 session.commit()
View Code
1 session.query(Users).filter(Users.id > 2).update({"name" : "099"})
2 session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
3 session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
4 session.commit()
View Code
1 ret = session.query(Users).all()
2 ret = session.query(Users.name, Users.extra).all()
3 ret = session.query(Users).filter_by(name='alex').all()
4 ret = session.query(Users).filter_by(name='alex').first()
View Code
  • 其他
 1 # 条件
 2 ret = session.query(Users).filter_by(name='alex').all()
 3 ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
 4 ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
 5 ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
 6 ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
 7 ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()
 8 from sqlalchemy import and_, or_
 9 ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
10 ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
11 ret = session.query(Users).filter(
12     or_(
13         Users.id < 2,
14         and_(Users.name == 'eric', Users.id > 3),
15         Users.extra != ""
16     )).all()
17 
18 
19 # 通配符
20 ret = session.query(Users).filter(Users.name.like('e%')).all()
21 ret = session.query(Users).filter(~Users.name.like('e%')).all()
22 
23 # 限制
24 ret = session.query(Users)[1:2]
25 
26 # 排序
27 ret = session.query(Users).order_by(Users.name.desc()).all()
28 ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()
29 
30 # 分组
31 from sqlalchemy.sql import func
32 
33 ret = session.query(Users).group_by(Users.extra).all()
34 ret = session.query(
35     func.max(Users.id),
36     func.sum(Users.id),
37     func.min(Users.id)).group_by(Users.name).all()
38 
39 ret = session.query(
40     func.max(Users.id),
41     func.sum(Users.id),
42     func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()
43 
44 # 连表
45 
46 ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()
47 
48 ret = session.query(Person).join(Favor).all()
49 
50 ret = session.query(Person).join(Favor, isouter=True).all()
51 
52 
53 # 组合
54 q1 = session.query(Users.name).filter(Users.id > 2)
55 q2 = session.query(Favor.caption).filter(Favor.nid < 2)
56 ret = q1.union(q2).all()
57 
58 q1 = session.query(Users.name).filter(Users.id > 2)
59 q2 = session.query(Favor.caption).filter(Favor.nid < 2)
60 ret = q1.union_all(q2).all()
View Code

 

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 from sqlalchemy import create_engine,and_,or_,func,Table
  4 from sqlalchemy.ext.declarative import declarative_base
  5 from sqlalchemy import Column, Integer, String,ForeignKey,UniqueConstraint,DateTime
  6 from  sqlalchemy.orm import sessionmaker,relationship
  7 
  8 Base = declarative_base() #生成一个SqlORM 基类
  9 
 10 # 服务器账号和组
 11 # HostUser2Group = Table('hostuser_2_group',Base.metadata,
 12 #     Column('hostuser_id',ForeignKey('host_user.id'),primary_key=True),
 13 #     Column('group_id',ForeignKey('group.id'),primary_key=True),
 14 # )
 15 
 16 # 用户和组关系表,用户可以属于多个组,一个组可以有多个人
 17 UserProfile2Group = Table('userprofile_2_group',Base.metadata,
 18     Column('userprofile_id',ForeignKey('user_profile.id'),primary_key=True),
 19     Column('group_id',ForeignKey('group.id'),primary_key=True),
 20 )
 21 
 22 # 程序登陆用户和服务器账户,一个人可以有多个服务器账号,一个服务器账号可以给多个人用
 23 UserProfile2HostUser= Table('userprofile_2_hostuser',Base.metadata,
 24     Column('userprofile_id',ForeignKey('user_profile.id'),primary_key=True),
 25     Column('hostuser_id',ForeignKey('host_user.id'),primary_key=True),
 26 )
 27 
 28 
 29 class Host(Base):
 30     __tablename__='host'
 31     id = Column(Integer,primary_key=True,autoincrement=True)
 32     hostname = Column(String(64),unique=True,nullable=False)
 33     ip_addr = Column(String(128),unique=True,nullable=False)
 34     port = Column(Integer,default=22)
 35     def __repr__(self):
 36         return  "<id=%s,hostname=%s, ip_addr=%s>" %(self.id,
 37                                                     self.hostname,
 38                                                     self.ip_addr)
 39 
 40 
 41 class HostUser(Base):
 42     __tablename__ = 'host_user'
 43     id = Column(Integer,primary_key=True)
 44     AuthTypes = [
 45         (u'ssh-passwd',u'SSH/Password'),
 46         (u'ssh-key',u'SSH/KEY'),
 47     ]
 48     # auth_type = Column(ChoiceType(AuthTypes))
 49     auth_type = Column(String(64))
 50     username = Column(String(64),unique=True,nullable=False)
 51     password = Column(String(255))
 52 
 53     host_id = Column(Integer,ForeignKey('host.id'))
 54     
 55     # groups = relationship('Group',
 56     #                       secondary=HostUser2Group,
 57     #                       backref='host_list')
 58 
 59     __table_args__ = (UniqueConstraint('host_id','username', name='_host_username_uc'),)
 60 
 61     def __repr__(self):
 62         return  "<id=%s,name=%s>" %(self.id,self.username)
 63 
 64 
 65 class Group(Base):
 66     __tablename__ = 'group'
 67     id = Column(Integer,primary_key=True)
 68     name = Column(String(64),unique=True,nullable=False)
 69     def __repr__(self):
 70         return  "<id=%s,name=%s>" %(self.id,self.name)
 71 
 72 
 73 class UserProfile(Base):
 74     __tablename__ = 'user_profile'
 75     id = Column(Integer,primary_key=True)
 76     username = Column(String(64),unique=True,nullable=False)
 77     password = Column(String(255),nullable=False)
 78     # host_list = relationship('HostUser',
 79     #                       secondary=UserProfile2HostUser,
 80     #                       backref='userprofiles')
 81     # groups = relationship('Group',
 82     #                       secondary=UserProfile2Group,
 83     #                       backref='userprofiles')
 84     def __repr__(self):
 85         return  "<id=%s,name=%s>" %(self.id,self.username)
 86 
 87 
 88 class AuditLog(Base):
 89     __tablename__ = 'audit_log'
 90     id = Column(Integer,primary_key=True)
 91     userprofile_id = Column(Integer,ForeignKey('user_profile.id'))
 92     hostuser_id = Column(Integer,ForeignKey('host_user.id'))
 93     action_choices2 = [
 94         (u'cmd',u'CMD'),
 95         (u'login',u'Login'),
 96         (u'logout',u'Logout'),
 97     ]
 98     action_type = Column(ChoiceType(action_choices2))
 99     #action_type = Column(String(64))
100     cmd = Column(String(255))
101     date = Column(DateTime)
102 
103     # user_profile = relationship("UserProfile")
104     #bind_host = relationship("BindHost")
105 
106 
107 engine = create_engine("mysql+pymsql://root:123@localhost:3306/stupid_jumpserver",echo=False)
108 Base.metadata.create_all(engine) #创建所有表结构
109 
110 表结构操作联系
表结构操作联系

 

posted @ 2017-05-11 17:05  浮光掠影转瞬间  阅读(588)  评论(0编辑  收藏  举报