• 3.Flask-SQLAlchemy


     (1)安装

    pip install flask_sqlalchemy

    (2)数据库连接

    from flask import Flask
    # 1.导入
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    #2.定义要连接的数据库
    DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
    #3.添加到到配置中
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =False
    # 4.实例化一个对象,将app传进去 db = SQLAlchemy(app) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()

    (3)创建表

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    
    class User(db.Model):
        __tablename__ = 'user'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        username = db.Column(db.String(50),nullable=False)
    
    
    class Article(db.Model):
        __tablename__ = "article"
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        title = db.Column(db.String(50), nullable=False)
        uid = db.Column(db.Integer,db.ForeignKey("user.id"))
        author = db.relationship("User",backref='article')
    
    db.drop_all()         #删除表
    db.create_all()       #创建表
    
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    if __name__ == '__main__':
        app.run()

     (4)添加数据

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    
    class User(db.Model):
        __tablename__ = 'user'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        username = db.Column(db.String(50),nullable=False)
    
    
    class Article(db.Model):
        __tablename__ = "article"
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        title = db.Column(db.String(50), nullable=False)
        uid = db.Column(db.Integer,db.ForeignKey("user.id"))
        author = db.relationship("User",backref='article')
    
    # db.drop_all()         #删除表
    # db.create_all()       #创建表
    
    #添加数据
    user = User(username='derek')
    article = Article(title='今天5/27号')
    article.author = user
    
    db.session.add(article)
    db.session.commit()
    
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    if __name__ == '__main__':
        app.run()

     (5)查看、修改和删除

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/learn_sqlalchemy?charset=utf8"
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    
    class User(db.Model):
        __tablename__ = 'user'
        id = db.Column(db.Integer,primary_key=True,autoincrement=True)
        username = db.Column(db.String(50),nullable=False)
    
        def __repr__(self):
            return "<username:%s>"%self.username
    
    class Article(db.Model):
        __tablename__ = "article"
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        title = db.Column(db.String(50), nullable=False)
        uid = db.Column(db.Integer,db.ForeignKey("user.id"))
        author = db.relationship("User",backref='article')
    
    # db.drop_all()         #删除表
    # db.create_all()       #创建表
    
    # 1.添加数据
    # user = User(username='derek')
    # article = Article(title='今天5/27号')
    # article.author = user
    #
    # db.session.add(article)
    # db.session.commit()
    
    # 2.查询数据
    # users=User.query.all()
    # print(users)
    
    # 3.修改数据,先查找出来再修改
    # user = User.query.filter(User.username=='derek').first()
    # user.username = 'jack'
    # db.session.commit()
    
    # 4.删除数据
    user = User.query.filter(User.username=='jack').first()
    db.session.delete(user)
    db.session.commit()
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    if __name__ == '__main__':
        app.run()
     
  • 相关阅读:
    阿里云POLARDB荣膺2019中国数据库年度最佳创新产品
    实时大数据开发难、运维难、应用难?来,一站解决!
    阿里云应用实时监控 ARMS 再升级,支持 Prometheus 开源生态
    一线实践 | 借助混沌工程工具 ChaosBlade 构建高可用的分布式系统
    使用DataX同步MaxCompute数据到TableStore(原OTS)优化指南
    Twitter 宣布抛弃 Mesos,全面转向Kubernetes
    阿里云Kubernetes服务上使用Tekton完成应用发布初体验
    Knative Tracing 介绍
    不断被取代的传统职业:快速发展的智能交互
    bzoj1433: [ZJOI2009]假期的宿舍
  • 原文地址:https://www.cnblogs.com/gaidy/p/11887051.html
Copyright © 2020-2023  润新知