smysql
a. 下載安裝 pip3 install flask-sqlalchemy b. chun.__init__.py 導入並實例化SQLAlchemy from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() 注意事項: - 必須在導入藍圖以前 - 必須導入models.py c. 初始化 db.init_app(app) d. 在配置文件中寫入配置 # ##### SQLALchemy配置文件 ##### SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/s9day122?charset=utf8" SQLALCHEMY_POOL_SIZE = 10 SQLALCHEMY_MAX_OVERFLOW = 5 e. 建立models.py中的類(對應數據庫表) chun/models.py from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy import Integer,String,Text,Date,DateTime from sqlalchemy import create_engine from chun import db class Users(db.Model): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) depart_id = Column(Integer) f. 生成表(使用app上下文) from chun import db,create_app app = create_app() app_ctx = app.app_context() # app_ctx = app/g with app_ctx: # __enter__,經過LocalStack放入Local中 db.create_all() # 調用LocalStack放入Local中獲取app,再去app中獲取配置 g. 基於ORM對數據庫進行操做。 from flask import Blueprint from chun import db from chun import models us = Blueprint('us',__name__) @us.route('/index') def index(): # 使用SQLAlchemy在數據庫中插入一條數據 # db.session.add(models.Users(name='高件套',depart_id=1)) # db.session.commit() # db.session.remove() result = db.session.query(models.Users).all() print(result) db.session.remove() return 'Index'