ORM框架之SQLAlchemy
一、SQLAlchemy的简介
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
二、SQLAlchemy的初步应用---表的创建
1、单表的创建与删除
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
import time
#创建继承类Base(规定的写法)
Base = declarative_base()
#创建类,并继承父类Base
class User(Base):
#创建表,“__talbename__”后的值代表数据库表名
__tablename__ = 'user'
#创建数据库表的列字段
id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(32))
age = Column(Integer)
#创建索引
__table_args__ = (
UniqueConstraint('id', 'name', name='uix_id_name'),
Index('uix_id_name', 'name')
)
def init_db():
#创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#找到所有继承Base这个类的子类,并创建子类中定义的所有的数据库表
Base.metadata.create_all(engine)
def drop_db():
# 创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
# 找到所有继承Base这个类的子类,并删除子类中定义的所有的数据库表
Base.metadata.drop_all(engine)
#执行函数,创建数据库表
init_db()
time.sleep(1)
print("数据库表创建成功!")
#执行函数,删除数据库表
drop_db()
time.sleep(1)
print("数据库表删除成功!")
2、一对多
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
import time
#创建继承类Base(规定的写法)
Base = declarative_base()
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True)#设置为主键
caption = Column(String(50), default='red', unique=True)#默认值为red,设置为唯一约束
class Person(Base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)#设置为主键
name = Column(String(32), index=True, nullable=True)#可以为空
favor_id = Column(Integer, ForeignKey("favor.nid"))#设置外键,person.favor.id = favor.id
#创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#找到所有继承Base这个类的子类,并创建子类中定义的所有的数据库表
Base.metadata.create_all(engine)
3、多对多
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
import time
#创建继承类Base(规定的写法)
Base = declarative_base()
# 多对多
class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False)
class Server(Base):
__tablename__ = 'server'
id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False)
port = Column(Integer, default=22)
class ServerToGroup(Base):
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
server_id = Column(Integer, ForeignKey('server.id'))#设置外键 servertogroup.server_id = server.id
group_id = Column(Integer, ForeignKey('group.id'))#设置外键 servertogroup.group_id = group.id
def init_db():
# 创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
# 找到所有继承Base这个类的子类,并创建子类中定义的所有的数据库表
Base.metadata.create_all(engine)
def drop_db():
# 创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
# 找到所有继承Base这个类的子类,并删除子类中定义的所有的数据库表
Base.metadata.drop_all(engine)
# 执行函数,创建数据库表
init_db()
time.sleep(1)
print("数据库表创建成功!")
#执行函数,删除数据库表
drop_db()
time.sleep(1)
print("数据库表删除成功!")
三、SQLAlchemy的进一步应用---表的操作
1、添加数据
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
#创建继承类Base(规定的写法)
Base = declarative_base()
#创建类,并继承父类Base
class User(Base):
#创建表,“__talbename__”后的值代表数据库表名
__tablename__ = 'user'
#创建数据库表的列字段
id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(32))
age = Column(Integer)
#创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#找到所有继承Base这个类的子类,并创建子类中定义的所有的数据库表
#Base.metadata.create_all(engine)
#创建session会话
Session = sessionmaker(bind = engine)
session = Session()
#实例化类对象,并添加到session中
obj = User(name = "alex1",age = 35)#添加单条数据
session.add(obj)
#添加多条数据
session.add_all([
User(name = "alex2",age = 100),
User(name = "alex3",age = 90),
])
#提交数据
session.commit()
2、删除数据
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
#创建继承类Base(规定的写法)
Base = declarative_base()
#创建类,并继承父类Base
class User(Base):
#创建表,“__talbename__”后的值代表数据库表名
__tablename__ = 'user'
#创建数据库表的列字段
id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(32))
age = Column(Integer)
#创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#创建session会话
Session = sessionmaker(bind = engine)
session = Session()
#删除数据,query后边是类名,filter后面跟的是where条件
session.query(User).filter(User.id > 3).delete()
#提交数据
session.commit()
3、修改数据
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
#创建继承类Base(规定的写法)
Base = declarative_base()
#创建类,并继承父类Base
class User(Base):
#创建表,“__talbename__”后的值代表数据库表名
__tablename__ = 'user'
#创建数据库表的列字段
id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(32))
age = Column(Integer)
#创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#创建session会话
Session = sessionmaker(bind = engine)
session = Session()
#修改数据,query后边是类名,filter后面跟的是where条件,update后面跟的是修改的字段及字段内容
session.query(User).filter(User.id > 2).update({User.age:User.age + 10},synchronize_session="evaluate")
#提交数据
session.commit()
4、查询数据
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
#创建继承类Base(规定的写法)
Base = declarative_base()
#创建类,并继承父类Base
class User(Base):
#创建表,“__talbename__”后的值代表数据库表名
__tablename__ = 'user'
#创建数据库表的列字段
id = Column(Integer,primary_key=True,autoincrement=True)
name = Column(String(32))
age = Column(Integer)
#创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#创建session会话
Session = sessionmaker(bind = engine)
session = Session()
#查询数据,query后边是类名
result_sql = session.query(User)#结果是生成的sql语句
print("result_sql:",result_sql)#SELECT user.id AS user_id, user.name AS user_name, user.age AS user_age FROM user
result_obj = session.query(User).all()#查询出来的是符合条件的User对象
print("result_obj:",result_obj)#[<__main__.User object at 0x00000004E0A6EA58>, <__main__.User object at 0x00000004E0A6E9E8>, <__main__.User object at 0x00000004E0A6EFD0>]
#将结果打印
for result in result_obj:
print("user_id:",result.id)
print("user_name:",result.name)
#提交数据
session.commit()
注:查询的其他方式:filter_by内部调用filter
session = session.query(User.name, User.age).all()#查询user表中name、age列
session.query(User).filter_by(name='alex').all()#查询user表中name是alex的所有行
session.query(User).filter_by(name='alex').first()#查询user表中name是alex的第一行数据
5、其他查询条件
# 条件 ret = session.query(Users).filter_by(name='alex').all() ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all() ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()#相当于Users.id >1 and Users.id < 3 and Users.name == eric ret = session.query(Users).filter(Users.id.in_([1,3,4])).all() ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()#~表示非 ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()#相当于select * from Users where Users.id in (select * from ...) from sqlalchemy import and_, or_ ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all() ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all() ret = session.query(Users).filter(#先进行最里面括号中的and连接,然后再进行外面括号的or连接 or_( Users.id < 2, and_(Users.name == 'eric', Users.id > 3), Users.extra != "" )).all() # 通配符 ret = session.query(Users).filter(Users.name.like('e%')).all()#模糊查询 ret = session.query(Users).filter(~Users.name.like('e%')).all() # 限制 ret = session.query(Users)[1:2] # 排序 ret = session.query(Users).order_by(Users.name.desc()).all() ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all() # 分组 from sqlalchemy.sql import func ret = session.query(Users).group_by(Users.extra).all() ret = session.query( func.max(Users.id),#最大值 func.sum(Users.id),#求和 func.min(Users.id)).group_by(Users.name).all()#最小值 ret = session.query( func.max(Users.id), func.sum(Users.id), func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all() # 连表 ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all() ret = session.query(Person).join(Favor).all() ret = session.query(Person).join(Favor, isouter=True).all() # 组合 q1 = session.query(Users.name).filter(Users.id > 2) q2 = session.query(Favor.caption).filter(Favor.nid < 2) ret = q1.union(q2).all()#组合并去重 q1 = session.query(Users.name).filter(Users.id > 2) q2 = session.query(Favor.caption).filter(Favor.nid < 2) ret = q1.union_all(q2).all()#组合不去重
6、多表查询
a.relationship的应用
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:ye
#导入模块
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
import time
#创建继承类Base(规定的写法)
Base = declarative_base()
# 多对多
class Department(Base):
__tablename__ = 'department'
id = Column(Integer, primary_key=True)
depart_name = Column(String(64), unique=True, nullable=False)
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True, autoincrement=True)
user_name = Column(String(64), unique=True, nullable=False)
user_depart_id = Column(Integer, ForeignKey('department.id'))#通过此外键进行关联
#创建两表之间的连接
depart = relationship("Department",backref="pers")
# 创建引擎,并在此基础上通过pymysql插件,连接数据库。同时创建数据库连接池,设置为5
engine = create_engine("mysql+pymysql://root:oldboy@192.168.159.134:3306/day15?charset=utf8", max_overflow=5)
#Base.metadata.create_all(engine)
#创建session会话
Session = sessionmaker(bind = engine)
session = Session()
result_obj = session.query(Person).all()
for result in result_obj:
print("person.id:",result.id)
print("person.user_name:", result.user_name)
print("depart_name:",result.depart.depart_name)
b.session.add的应用
#创建session会话
Session = sessionmaker(bind = engine)
session = Session()
#通过session在多表中插入数据
session.add(Person(id=10,user_name='sb',depart=Department(id=9,depart_name="湖南")))
session.commit()