• SQLAlchemy ORM方式操作


    SQLAlchemy-ORM方式操作

    SQLAlchemy ORM方式操作

    1. 引入所需模块

      # 创建引擎
      from sqlalchemy import create_engine
      # 引入模型基类声明函数
      from sqlalchemy.ext.declarative import declarative_base
      # 引入列类和基本数据类型
      from sqlalchemy import Column, ForeignKey, Integer, String
      # 引入Session类
      from sqlalchemy.orm import Session
      
    2. 初始操作

      # 创建引擎
      engine = create_engine('sqlite://', echo=True)
      
      # 创建(实例化一个类)基类
      Base = declarative_base()
      
    3. 建立会话

      # 实例化Session
      session = Session(bind=engine)
      
    4. 主要操作

      # 参加其他部分
      
    5. 结束会话

      # 结束(关闭)会话
      session.close()
      
    6. 释放资源

      # 销毁引擎
      engine.dispose()
      

    Session实例化方式

    1. 使用sessionmaker(),实例化时绑定(bind)引擎(engine)

      from sqlalchemy import create_engine
      # 引入session创造器
      from sqlalchemy.orm import sessionmaker
      
      engine = create_engine('sqlite://', echo=True)
      # 实例化Session类
      Session = sessionmaker(bind=engine)
      # 实例化Session
      session = Session()
      
    2. 使用sessionmaker(),后期配置(configure())引擎(engine)

      from sqlalchemy import create_engine
      from sqlalchemy.orm import sessionmaker
      
      Session = sessionmaker()
      
      engine = create_engine('sqlite://', echo=True)
      Session.configure(bind=engine)
      
      session = Session()
      
    3. 直接使用sqlalchemy.orm.Session

      from sqlalchemy import create_engine
      from sqlalchemy.orm import Session
      
      engine = create_engine('sqlite://', echo=True)
      
      session = Session(engine)
      
  • 相关阅读:
    Working with WordprocessingML documents (Open XML SDK)
    How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
    Azure:Manage anonymous read access to containers and blobs
    Convert HTML to PDF with New Plugin
    location.replace() keeps the history under control
    On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API
    HTTP Modules versus ASP.NET MVC Action Filters
    解读ASP.NET 5 & MVC6系列(6):Middleware详解
    Content Negotiation in ASP.NET Web API
    Action Results in Web API 2
  • 原文地址:https://www.cnblogs.com/cp9648/p/10415674.html
Copyright © 2020-2023  润新知