what‘s the 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:[email protected]:port/dbname[?key=value&key=value...] 更多:http://docs.sqlalchemy.org/en/latest/dialects/index.html
使用SQLAlchemy
一、利用原生SQL语句进行操作
利用原生SQL语句进行是一种操作方式,但其实平常我们并不适用这种方式。
import time import threading import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.engine.base import Engine engine = create_engine( "mysql+pymysql://root:[email protected]: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()
#!/usr/bin/env python # -*- coding:utf-8 -*- import time import threading import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.engine.base import Engine engine = create_engine("mysql+pymysql://root:[email protected]: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()
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]: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()
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]: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":‘wupeiqi‘}) session.commit() print(cursor.lastrowid) session.close()
二、ORM
flask是轻量级框架,所以本身并不具备ORM。想要操作数据库就必须配合着SQLAlchemy来使用。
注:SQLAlchemy创建的表默认引擎不是InnoDB,若想改成InnoDB只要加一条参数即可
class User(BaseModel): __table_args__ = { ‘mysql_engine‘: ‘InnoDB‘, ‘mysql_charset‘: ‘utf8‘ }
创建单表:
#!/usr/bin/env python # -*- coding:utf-8 -*- 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‘#表名,与Django不同的是,flask必须写 id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) # email = Column(String(32), unique=True) # 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:[email protected]:3306/s6?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:[email protected]:3306/s6?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()
创建多表(包含FK和M2M两种可能):
#!/usr/bin/env python # -*- coding:utf-8 -*- 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 from sqlalchemy.orm import relationship Base = declarative_base() # ##################### 单表示例 ######################### class Users(Base): __tablename__ = ‘users‘ id = Column(Integer, primary_key=True) name = Column(String(32), index=True) age = Column(Integer, default=18) email = Column(String(32), unique=True) 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‘, ‘extra‘), ) class Hosts(Base): __tablename__ = ‘hosts‘ id = Column(Integer, primary_key=True) name = Column(String(32), index=True) ctime = Column(DateTime, default=datetime.datetime.now) # ##################### 一对多示例 ######################### 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_id = Column(Integer, ForeignKey("hobby.id"))#外键 # 与生成表结构无关,仅用于查询方便,backref相当于Django的related_name hobby = relationship("Hobby", backref=‘pers‘) # ##################### 多对多示例 ######################### #与Django不同,flask中多对多的第三张表必须自己手动创建 class Server2Group(Base): __tablename__ = ‘server2group‘ id = Column(Integer, primary_key=True, autoincrement=True) server_id = Column(Integer, ForeignKey(‘server.id‘)) group_id = Column(Integer, ForeignKey(‘group.id‘)) class Group(Base): __tablename__ = ‘group‘ id = Column(Integer, primary_key=True) name = Column(String(64), unique=True, nullable=False) # 与生成表结构无关,仅用于查询方便,secondary指的是第三张表的表名 servers = relationship(‘Server‘, secondary=‘server2group‘, backref=‘groups‘) class Server(Base): __tablename__ = ‘server‘ id = Column(Integer, primary_key=True, autoincrement=True) hostname = Column(String(64), unique=True, nullable=False) def init_db(): """ 根据类创建数据库表 :return: """ engine = create_engine( "mysql+pymysql://root:1[email protected]:3306/s6?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:[email protected]:3306/s6?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()
基本增删改查示例:
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]: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="wupeiqi"), Users(name="alex"), Hosts(name="c1.com"), ]) session.commit()#提交(不执行这步,上述操作都无效) """ # ################ 删除 ################ """ session.query(Users).filter(Users.id > 2).delete()#删除操作 session.commit()#提交 """ # ################ 修改 ################ """ #synchronize_session是用来说明相加时时数字类型的相加还是字符串类型的相加 session.query(Users).filter(Users.id > 0).update({"name" : "099"}) 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()#提交 """ # ################ 查询 ################ """ #filter_by的后面的括号直接写字段=条件,类似Django。filter则需写表名.字段==条件 r1 = session.query(Users).all() r2 = session.query(Users.name.label(‘xx‘), Users.age).all() r3 = session.query(Users).filter(Users.name == "alex").all() r4 = session.query(Users).filter_by(name=‘alex‘).all() r5 = session.query(Users).filter_by(name=‘alex‘).first() #占位符操作示例 r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name=‘fred‘).order_by(Users.id).all() r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name=‘ed‘).all() """ session.close()#操作commit后,需将链接关闭
其他常用的查询操作(条件查询、模糊查询、排序、分组、连表、组合)
# 条件 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() 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_ 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() # 通配符 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()
进阶
基于scop-session创建连接可以增加多线程操作的安全
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]:3306/s6", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) """ # 方式一:由于无法提供线程共享功能,所有在开发时要注意,在每个线程中自己创建 session。 # from sqlalchemy.orm.session import Session # 自己具有操作数据库的:‘close‘, ‘commit‘, ‘connection‘, ‘delete‘, ‘execute‘, ‘expire‘,..... session = SessionFactory() # print(‘原生session‘,session) # 操作 session.close() """ """ # 线程安全,基于本地线程实现每个线程用同一个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‘ ) """ session = scoped_session(Session) # ############# 执行ORM操作 ############# obj1 = Users(name="alex1") session.add(obj1) # 提交事务 session.commit() # 关闭session session.remove()#我们不一样
连表查询FK
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]: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) """ session.close() 基于relationship操作ForeignKey
连表查询M2M
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]: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() 基于relationship操作m2m
关联子查询
#!/usr/bin/env python # -*- coding:utf-8 -*- 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:[email protected]:3306/s6?charset=utf8", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) session = Session() # 关联子查询 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` """ # 原生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() 其他
Flask-SQLAlchemy
flask-sqlalchemy 是在 sqlalchemy 的基础上,提供了一些常用的工具,并预设了一些默认值,帮助你=我们更轻松地完成常见任务。
flask-sqlalchemy 用起来比直接用 sqlalchemy 方便、省事,不过有些高级一点的功能如果不了解 sqlalchemy 的话会用不好。
下面我们来详述flask-sqlalchemy的操作方法
# 1. 引入Flask-SQLAlchemy from flask_sqlalchemy import SQLAlchemy # 2.实例化一个SQLAlchemy对象 """ 实例化方式一: 在函数里面,SQLAlchemy(app) #如果想在其他地方使用这种方式就不好使了,所以推荐使用方式二 """ #方式二 db = SQLAlchemy()#在全局中创建实例化 db.init_app(app) #在函数中调用init_app方法吧app放进去了 # 3. 导入models中的表 from .models import * #4. 在需要创建表的文件中导入db.model,所有的表再创建时继承db.model #5. 借助Flask-Migrate组件来完成表的生成 """ 安装 pip3 install Flask-Migrate # 5.1 导入 from flask_migrate import Migrate, MigrateCommand from app import create_app, db app = create_app() manager = Manager(app) # 5.2 创建migrate示例 migrate = Migrate(app, db) # 5.3 创建db命令 manager.add_command(‘db‘, MigrateCommand) """ #上述代码完毕后,我们就可以在命令终端敲入类似Django的终端代码在数据库生成表了 python manage.py db init#只需初次创建库时敲 #以下两行代码在每次对数据库中的表进行修改时都需执行(数据库迁移) python manage.py db migrate#功能与Django的python manage.py db makemigrations相同 python manage.py db upgrade#功能与Django的python manage.py db migrate相同 #以后执行SQL时,我们就可以实现与Django类似的ORM操作了: #方式一: result = db.session.query(models.User.id,models.User.name).all() db.session.remove() #方式二: result = models.Users.query.all()