SQLAlchemy

Posted cs_1993

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLAlchemy相关的知识,希望对你有一定的参考价值。

介绍

SQLAlchemy是一个基于Python实现的ORM框架。该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数据API执行SQL并获取执行结果。

安装

pip3 install sqlalchemy

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库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...]
    
更多:http://docs.sqlalchemy.org/en/latest/dialects/index.html

使用

1、创建表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
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
 
engine = create_engine(
"mysql+pymysql://root:123@127.0.0.1:3306/t1?charset=utf8",
 max_overflow=5 # 超过连接池大小外最多创建的连接
 pool_siez = 5     # 连接池大小
 pool_timeout = 30 # 池中没有线程最多等待的时间,否则报错,
 pool_recycle = 1  # 多久之后对线程池中的线程进行一次连接的回收
 )
 
 
Base = declarative_base()
 
# 创建单表
class Users(Base):
    __tablename__ = users
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    extra = Column(String(16))
 
    __table_args__ = (
    UniqueConstraint(id, name, name=uix_id_name),
        Index(ix_id_name, name, extra),
    )
 
 
# 一对多
class Favor(Base):
    __tablename__ = favor
    nid = Column(Integer, primary_key=True)
    caption = Column(String(50), default=red, unique=True)
 
 
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"))
 
 
# 多对多
class Group(Base):
    __tablename__ = group
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    port = Column(Integer, default=22)
 
 
class Server(Base):
    __tablename__ = server
 
    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)
 
 
class ServerToGroup(Base):
    __tablename__ = servertogroup
    nid = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey(server.id))
    group_id = Column(Integer, ForeignKey(group.id))
 
 # 初始化数据库
def init_db():
    Base.metadata.create_all(engine)
 
 
def drop_db():
    Base.metadata.drop_all(engine)
    

2、操作表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
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

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)

Base = declarative_base()

# 创建单表
class Users(Base):
    __tablename__ = users
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    extra = Column(String(16))

    __table_args__ = (
    UniqueConstraint(id, name, name=uix_id_name),
        Index(ix_id_name, name, extra),
    )

    def __repr__(self):
        return "%s-%s" %(self.id, self.name)

# 一对多
class Favor(Base):
    __tablename__ = favor
    nid = Column(Integer, primary_key=True)
    caption = Column(String(50), default=red, unique=True)

    def __repr__(self):
        return "%s-%s" %(self.nid, self.caption)

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"))
    # 与生成表结构无关,仅用于查询方便
    favor = relationship("Favor", backref=pers)

# 多对多
class ServerToGroup(Base):
    __tablename__ = servertogroup
    nid = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey(server.id))
    group_id = Column(Integer, ForeignKey(group.id))
    group = relationship("Group", backref=s2g)
    server = relationship("Server", backref=s2g)

class Group(Base):
    __tablename__ = group
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    port = Column(Integer, default=22)
    # group = relationship(‘Group‘,secondary=ServerToGroup,backref=‘host_list‘)


class Server(Base):
    __tablename__ = server

    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)




def init_db():
    """创建所有定义的表到数据库中"""
    Base.metadata.create_all(engine)


def drop_db():
     """从数据库中删除所有定义的表"""
    Base.metadata.drop_all(engine)

# 执行创建表
#init_db()

# 创建会话实例对象
Session = sessionmaker(bind=engine)
session = Session()

增:

obj = Users(name="alex0", extra=sb)
session.add(obj)
session.add_all([
    Users(name="alex1", extra=sb),
    Users(name="alex2", extra=sb),
])
session.commit()

# 创建一个名称叫:IT部门, 再在该部门添加一个员工:田硕
方式一
d1 = Depart(title=IT)
session.add(d1)
session.commit()
u1 = User(name=田硕,depart_id=d1.id)
session.add(u1)
session.commit()

方式二
u1 = User(name=田硕,dp=Depart(title=IT)
session.add(u1)
session.commit()

# 创建一个叫财务的部门,再在部门添加多个员工
d1 = Depart(title=财务)
d1.pers = [Users(name=harry, Users(name=jerry),]
session.add(d1)

# 创建一个课程,创建2学生。两个学生选新创建的课程
obj = ourse(title=英语)
obj.student_list = [Student(name=harry),Student(sam)]

删:

session.query(Users).filter(Users.id > 2).delete()
session.commit()

查:

结果集内看到的是对象 、还是数据
? query(类名) 返回的就是对象
? query(类名.字段名) 返回的就是含有数据的元组对象

# 所有数据,且结果集中是一个一个的对象
# 结果 [obj1, obj2, obj3]
ret = session.query(Users).all()

#  指定字段查询,返回所有的数据,是一个列表,列表内是一个一个的元组
# 结果 [(‘yangge‘, ‘18‘), (‘qiangge‘, ‘19‘), (‘shark‘, ‘23‘)]
ret = session.query(Users.name, Users.extra).all()

#可以使用 label() 给每个列名起别名
for row in session.query(Teacher.name.label(t_name)).all():
    print(row.t_name)

filter_by() 接收的是关键字参数
filter() 允许使用 python 的比较或关系运算符,实现更灵活的查询
ret = session.query(Users).filter_by(name=alex).all()
ret = session.query(Users).filter_by(name=alex).first()
ret = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name=fred).order_by(User.id).all()
ret = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name=ed).all()

改:

session.query(Users).filter(Users.id > 2).update({"name" : "099"})
session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
#不同步,数据的更新在 commit 之后
session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()

其他:

(1)条件过滤

# 条件
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()
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()    # in 包含
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all() # not in
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name=eric))).all() 
# IS NOT NULL
query.filter(Teacher.name != None).all()
# 或者
query.filter(Teacher.name.isnot(None)).all()

from sqlalchemy import and_, or_
#AND过滤
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == eric)).all()
# OR 过滤
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == eric)).all()    # id 等于2或者name=eric
ret = session.query(Users).filter(
    or_(
        Users.id < 2,
        and_(Users.name == eric, Users.id > 3),
        Users.extra != ""
    )).all()
# AND 和 OR 的综合使用
query.filter(
    or_(
        Teacher.id <= 2,
        and_(Teacher.name == shark, Teacher.id > 3)
    )).all()

# 通配符
ret = session.query(Users).filter(Users.name.like(e%)).all()
ret = session.query(Users).filter(~Users.name.like(e%)).all()

(2)排序

# order by 排序
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()
# 正序
session.query(Teacher).order_by(Teacher.name).all()

# 倒序
session.query(Teacher).order_by(Teacher.name.desc()).all()

# 先按名字排序,假如有相同的再安装 id 排序
session.query(Teacher).order_by(Teacher.name, Teacher.id.desc()).all()

(3)分组

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()

(4)连表

ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()

ret = session.query(Person).join(Favor).all()
 
# isouter=True相当于left join
ret = session.query(Person).join(Favor, isouter=True).all()

ret = session.query(Users,Depart).join(Depart,Users.depart_id == Depart.id).all()

# 多对多连表
ret = session.query(Student2Course.id, Student.name).join(Student, Student2Course.student_id==student.id).join(Course,Student2Course.course_id==Course.id).order_by(Student2Course.id.asc())
for row in ret:

# 多对多反向查询
# 查找harry选有的课
obj = session.query(Studnet).filter(Student.name==harry).first()
for item in obj.course_list
    print(item.title)

# 查找选了生物课的所有人
obj = session.query(Course).filter(Course.title==生物).first()
for item in obj.student_list:
    print(item.name)

(4)统计

# 分组统计查询
from sqlalchemy.sql import func
# 统计表中所有的数据
session.query(func.count(*)).select_from(Teacher).first()

# 以年龄分组,并统计每组的数据数量
session.query(func.count(Teacher.age),Teacher.age.group_by(Teacher.age).all()

# 以年龄为分组,并统计每组的最大/最小 id 号,年龄总和/平均值,
session.query(
    func.max(Teacher.id),
    func.min(Teacher.id),
    func.sum(Teacher.age),
    func.avg(Teacher.age),
    Teacher.id
    ).group_by(Teacher.age).all()

# 从分组的数据中再查找需要的数据
session.query(
    func.max(Teacher.id),
    func.min(Teacher.age),
    func.sum(Teacher.age),
    func.avg(Teacher.age),
    Teacher.id
    ).group_by(Teacher.age).having(func.min(Teacher.id) > 2).all()

(5)嵌套查询

# 嵌套,从最内层的查询结果中再查询想要的数据
session.query(Teacher).filter(
    Teacher.id.in_(
        session.query(Teacher.id).filter_by(name=yangge))).all()

(6)组合

将两个查询结果结合到一起

# 组合  用一条数据将两个表中的要查询的数据组合在一张表里展示出来
q1 = session.query(Teacher.name).filter(Teacher.id > 2)
q2 = session.query(Student.name).filter(Student.id < 2)
## 去重
ret = q1.union(q2).all()
## 不去重 
q1 = session.query(Teacher.name).filter(Teacher.id > 2)
q2 = session.query(Student.name).filter(Student.id < 2)
ret = q1.union_all(q2).all()
        

 操作原生SQL

方式一:

import time
import threading
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine
 
engine = create_engine(
    "mysql+pymysql://root:123@127.0.0.1:3306/t1?charset=utf8",
    max_overflow=0,  # 超过连接池大小外最多创建的连接
    pool_size=5,  # 连接池大小
    pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
    pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
 
 
def task(arg):
    conn = engine.raw_connection()
    cursor = conn.cursor()
    cursor.execute(
        "select * from t1"
    )
    result = cursor.fetchall()
    cursor.close()
    conn.close()
 
 
for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

方式二:

import time
import threading
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine
from sqlalchemy.engine.result import ResultProxy
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=0, pool_size=5)

def task(arg):
    cur = engine.execute("select * from t1")
    result = cur.fetchall()
    cur.close()
    print(result)


for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

方式三:

import time
import threading
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.engine.base import Engine

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=0, pool_size=5)


def task(arg):
    conn = engine.contextual_connect()
    with conn:
        cur = conn.execute(
            "select * from t1"
        )
        result = cur.fetchall()
        print(result)


for i in range(20):
    t = threading.Thread(target=task, args=(i,))
    t.start()

数据库连接的两种方式

方式一:

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Student

engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/databasename?charset=utf8",
        max_overflow=0     # 超过连接池大小外最多创建的连接
        pool_size=5,       # 连接池大小
        pool_timeout=30 # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收)

SessionFactory = sessionmaker(bind=engine)


def task():
    # 去连接池获取一个连接
    session = SessionFactory()
    ret = session.query(Student).all()
    session.close()

方式二:(推荐使用,基于Threading.Locak实现)

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Student

engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/databasename?charset=utf8",
        max_overflow=0     # 超过连接池大小外最多创建的连接
        pool_size=5,       # 连接池大小
        pool_timeout=30 # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收)

SessionFactory = sessionmaker(bind=engine)
session = scoped_session(SessionFactory)

def task():
    ret = session.query(Student).all()
    session.remove()

 

以上是关于SQLAlchemy的主要内容,如果未能解决你的问题,请参考以下文章

SQLAlchemy的同步和异步的代码对比

SQLAlchemy的同步和异步的代码对比

SQLAlchemy的同步和异步的代码对比

SQLAlchemy:数据库创建代码小于数据库

python SQLAlchemy 缓存问题

python SQLAlchemy 缓存问题