第三方ORM 之 SQLAlchemy

weixin_34185364發表於2019-02-20

目錄

  1. 介紹
  2. 簡單使用
  3. 一對多關係
  4. 多對多關係
  5. 運算元據表
  6. 基於scoped_session實現執行緒安全
  7. 基本增刪改查
  8. 常用操作
  9. 執行原生sql
  10. 一對多
  11. 多對多
  12. 其他
  13. Flask-SQLAlchemy

1.介紹

SQLAlchemy是一個基於Python實現的ORM框架。該框架建立在 DB API之上,使用關係物件對映進行資料庫操作,簡言之便是:將類和物件轉換成SQL,然後使用資料API執行SQL並獲取執行結果。

pip3 install sqlalchemy
13223341-93abfb6f7fd34c7e.png
sqlalchemy框架

組成部分:

Engine,框架的引擎
Connection Pooling ,資料庫連線池
Dialect,選擇連線資料庫的DB API種類
Schema/Types,架構和型別
SQL Exprression Language,SQL表示式語言

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

2.簡單使用(能建立表,刪除表,不能修改表)

修改表:在資料庫新增欄位,類對應上

1執行原生sql(不常用)

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

engine = create_engine(
    "mysql+pymysql://root:123456@127.0.0.1:3306/test?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 app01_book"
    )
    result = cursor.fetchall()
    print(result)
    cursor.close()
    conn.close()

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

2 orm使用

models.py

import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'  # 資料庫表名稱
    id = Column(Integer, primary_key=True)  # id 主鍵
    name = Column(String(32), index=True, nullable=False)  # name列,索引,不可為空
    # email = Column(String(32), unique=True)
    #datetime.datetime.now不能加括號,加了括號,以後永遠是當前時間
    # ctime = Column(DateTime, default=datetime.datetime.now)
    # extra = Column(Text, nullable=True)

    __table_args__ = (
        # UniqueConstraint('id', 'name', name='uix_id_name'), #聯合唯一
        # Index('ix_id_name', 'name', 'email'), #索引
    )

def init_db():
    """
    根據類建立資料庫表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/aaa?charset=utf8",
        max_overflow=0,  # 超過連線池大小外最多建立的連線
        pool_size=5,  # 連線池大小
        pool_timeout=30,  # 池中沒有執行緒最多等待的時間,否則報錯
        pool_recycle=-1  # 多久之後對執行緒池中的執行緒進行一次連線的回收(重置)
    )

    Base.metadata.create_all(engine)

def drop_db():
    """
    根據類刪除資料庫表
    :return:
    """
    engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/aaa?charset=utf8",
        max_overflow=0,  # 超過連線池大小外最多建立的連線
        pool_size=5,  # 連線池大小
        pool_timeout=30,  # 池中沒有執行緒最多等待的時間,否則報錯
        pool_recycle=-1  # 多久之後對執行緒池中的執行緒進行一次連線的回收(重置)
    )

    Base.metadata.drop_all(engine)

if __name__ == '__main__':
    # drop_db()
    init_db()

app.py

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Users
#"mysql+pymysql://root@127.0.0.1:3306/aaa"
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/aaa", max_overflow=0, pool_size=5)
Connection = sessionmaker(bind=engine)

# 每次執行資料庫操作時,都需要建立一個Connection
con = Connection()

# ############# 執行ORM操作 #############
obj1 = Users(name="lqz")
con.add(obj1)
# 提交事務
con.commit()

# 關閉session,其實是將連線放回連線池
con.close()

3.一對多關係

class Hobby(Base):
    __tablename__ = 'hobby'
    id = Column(Integer, primary_key=True)
    caption = Column(String(50), default='籃球')


class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=True)
    # hobby指的是tablename而不是類名
    hobby_id = Column(Integer, ForeignKey("hobby.id"))
    
    # 跟資料庫無關,不會新增欄位,只用於快速連結串列操作
    # 類名,backref用於反向查詢
    hobby=relationship('Hobby',backref='pers')

4.多對多關係

class Boy2Girl(Base):
    __tablename__ = 'boy2girl'
    id = Column(Integer, primary_key=True, autoincrement=True)
    girl_id = Column(Integer, ForeignKey('girl.id'))
    boy_id = Column(Integer, ForeignKey('boy.id'))


class Girl(Base):
    __tablename__ = 'girl'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)


class Boy(Base):
    __tablename__ = 'boy'

    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)
    
    # 與生成表結構無關,僅用於查詢方便,放在哪個單表中都可以
    servers = relationship('Girl', secondary='boy2girl', backref='boys')

5.運算元據表

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Users
  
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/aaa", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
  
# 每次執行資料庫操作時,都需要建立一個session
session = Session()
  
# ############# 執行ORM操作 #############
obj1 = Users(name="lqz")
session.add(obj1)
  
# 提交事務
session.commit()
# 關閉session
session.close()

6.基於scoped_session實現執行緒安全

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from models import Users

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

"""
# 執行緒安全,基於本地執行緒實現每個執行緒用同一個session
# 特殊的:scoped_session中有原來方法的Session中的一下方法:

public_methods = (
    '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
    'close', 'commit', 'connection', 'delete', 'execute', 'expire',
    'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
    'is_modified', 'bulk_save_objects', 'bulk_insert_mappings',
    'bulk_update_mappings',
    'merge', 'query', 'refresh', 'rollback',
    'scalar'
)
"""
#scoped_session類並沒有繼承Session,但是卻又它的所有方法
session = scoped_session(Session)
# ############# 執行ORM操作 #############
obj1 = Users(name="alex1")
session.add(obj1)

# 提交事務
session.commit()
# 關閉session
session.close()

7.基本增刪查改

import time
import threading

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
from sqlalchemy.sql import text

from db import Users, Hosts

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

session = Session()

# ################ 新增 ################
"""
obj1 = Users(name="wupeiqi")
session.add(obj1)

session.add_all([
    Users(name="lqz"),
    Users(name="egon"),
    Hosts(name="c1.com"),
])
session.commit()
"""

# ################ 刪除 ################
"""
session.query(Users).filter(Users.id > 2).delete()
session.commit()
"""
# ################ 修改 ################
"""
#傳字典
session.query(Users).filter(Users.id > 0).update({"name" : "lqz"})
#類似於django的F查詢
session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False)
session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")
session.commit()
"""
# ################ 查詢 ################
"""
r1 = session.query(Users).all()
#只取age列,把name重新命名為xx
r2 = session.query(Users.name.label('xx'), Users.age).all()
#filter傳的是表示式,filter_by傳的是引數
r3 = session.query(Users).filter(Users.name == "lqz").all()
r4 = session.query(Users).filter_by(name='lqz').all()
r5 = session.query(Users).filter_by(name='lqz').first()
#:value 和:name 相當於佔位符,用params傳引數
r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(Users.id).all()
#自定義查詢sql
r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()
"""

#增,刪,改都要commit()
session.close()

8.常用操作

# 條件
ret = session.query(Users).filter_by(name='lqz').all()
#表示式,and條件連線
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()
#~非,除。。外
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()
from sqlalchemy import and_, or_
#or_包裹的都是or條件,and_包裹的都是and條件
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(
    or_(
        Users.id < 2,
        and_(Users.name == 'eric', Users.id > 3),
        Users.extra != ""
    )).all()


# 萬用字元,以e開頭,不以e開頭
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]

# 排序,根據name降序排列(從大到小)
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()
#分組之後取最大id,id之和,最小id
ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).all()
#haviing篩選
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()

# 連表(預設用forinkey關聯)

ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()
#join表,預設是inner join
ret = session.query(Person).join(Favor).all()
#isouter=True 外連,表示Person left join Favor,沒有右連線,反過來即可
ret = session.query(Person).join(Favor, isouter=True).all()
#列印原生sql
aa=session.query(Person).join(Favor, isouter=True)
print(aa)
# 自己指定on條件(連表條件),第二個引數,支援on多個條件,用and_,同上
ret = session.query(Person).join(Favor,Person.id==Favor.id, isouter=True).all()
# 組合(瞭解)UNION 操作符用於合併兩個或多個 SELECT 語句的結果集
#union和union 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()

9.執行原生sql

import time
import threading

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
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts

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

session = Session()

# 查詢
# cursor = session.execute('select * from users')
# result = cursor.fetchall()

# 新增
cursor = session.execute('insert into users(name) values(:value)',params={"value":'lqz'})
session.commit()
print(cursor.lastrowid)

session.close()

10.一對多

import time
import threading

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
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts, Hobby, Person

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
# 新增
"""
session.add_all([
    Hobby(caption='乒乓球'),
    Hobby(caption='羽毛球'),
    Person(name='張三', hobby_id=3),
    Person(name='李四', hobby_id=4),
])

person = Person(name='張九', hobby=Hobby(caption='姑娘'))
session.add(person)
#新增二
hb = Hobby(caption='人妖')
hb.pers = [Person(name='文飛'), Person(name='博雅')]
session.add(hb)

session.commit()
"""

# 使用relationship正向查詢
"""
v = session.query(Person).first()
print(v.name)
print(v.hobby.caption)
"""

# 使用relationship反向查詢
"""
v = session.query(Hobby).first()
print(v.caption)
print(v.pers)
"""
#方式一,自己連結串列
# person_list=session.query(models.Person.name,models.Hobby.caption).join(models.Hobby,isouter=True).all()
person_list=session.query(models.Person,models.Hobby).join(models.Hobby,isouter=True).all()
for row in person_list:
    # print(row.name,row.caption)
    print(row[0].name,row[1].caption)

#方式二:通過relationship

person_list=session.query(models.Person).all()
for row in person_list:
    print(row.name,row.hobby.caption)
#查詢喜歡姑娘的所有人
obj=session.query(models.Hobby).filter(models.Hobby.id==1).first()
persons=obj.pers
print(persons)
session.close()

11.多對多

import time
import threading

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
from sqlalchemy.sql import text
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts, Hobby, Person, Group, Server, Server2Group

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
# 新增
"""
session.add_all([
    Server(hostname='c1.com'),
    Server(hostname='c2.com'),
    Group(name='A組'),
    Group(name='B組'),
])
session.commit()

s2g = Server2Group(server_id=1, group_id=1)
session.add(s2g)
session.commit()


gp = Group(name='C組')
gp.servers = [Server(hostname='c3.com'),Server(hostname='c4.com')]
session.add(gp)
session.commit()


ser = Server(hostname='c6.com')
ser.groups = [Group(name='F組'),Group(name='G組')]
session.add(ser)
session.commit()
"""


# 使用relationship正向查詢
"""
v = session.query(Group).first()
print(v.name)
print(v.servers)
"""

# 使用relationship反向查詢
"""
v = session.query(Server).first()
print(v.hostname)
print(v.groups)
"""


session.close()

12.其它

import time
import threading

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
from sqlalchemy.sql import text, func
from sqlalchemy.engine.result import ResultProxy
from db import Users, Hosts, Hobby, Person, Group, Server, Server2Group

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6?charset=utf8", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()

# 關聯子查詢:correlate(Group)表示跟Group表做關聯,as_scalar相當於對該sql加括號,用於放在後面當子查詢
subqry = session.query(func.count(Server.id).label("sid")).filter(Server.id == Group.id).correlate(Group).as_scalar()
result = session.query(Group.name, subqry)
"""
SELECT `group`.name AS group_name, (SELECT count(server.id) AS sid 
FROM server 
WHERE server.id = `group`.id) AS anon_1 
FROM `group`
"""
'''

select * from tb where id in [select id from xxx];

select id,
        name,
        #必須保證此次查詢只有一個值
        (select max(id) from xxx) as mid
from tb

例如,第三個欄位只能有一個值
id name  mid
1  lqz   1,2  不合理
2  egon   2


'''


# 原生SQL
"""
# 查詢
cursor = session.execute('select * from users')
result = cursor.fetchall()

# 新增
cursor = session.execute('insert into users(name) values(:value)',params={"value":'wupeiqi'})
session.commit()
print(cursor.lastrowid)
"""

session.close()

13.Flask-SQLAlchemy

flask和SQLAchemy的管理者,通過他把他們做連線

db = SQLAlchemy()
    - 包含配置
    - 包含ORM基類
    - 包含create_all
    - engine
    - 建立連線

離線指令碼,建立表

詳見程式碼

相關文章