Flask learning (5)-the basic operation of the database

1. Addition, deletion and modification operations
1. Basic concepts

  • In Flask-SQLAlchemy, insert, modify, and delete operations are all managed by the database session.
    The session is represented by db.session. Before you are ready to write data to the database, you must first add the data to the session and then call the commit() method to submit the session.
  • In Flask-SQLAlchemy, the query operation is to manipulate data through the query object.
    The most basic query is to return all the data in the table, and you can use filters to perform more precise database queries.
db.session.add(role)    添加到数据库的session中
db.session.add_all([user1, user2]) 添加多个信息到session中
db.session.commit()     提交数据库的修改(包括增//)
db.session.rollback()   数据库的回滚操作
db.session.delete(user) 删除数据库(需跟上commit)

2. Example
app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# 配置数据库地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/nms_db'
# 跟踪数据库的修改 --> 不建议开启,未来的版本中会移除
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)
'''
两张表
角色(管理员/普通用户)
用户(角色ID)
'''


# 数据库的模型,需要继承db.Model
class Role(db.Model):
    # 定义表名
    __tablename__ = 'role'

    # 定义字段
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(16), unique=True)

    # 在一的一方,写关联
    # user = db.relationship('User'): 表示和User模型发生了关联,增加了一个user属性
    # backref='role': 表示role是User要用的属性
    user = db.relationship('User', backref='role')


class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(16), unique=True)
    email = db.Column(db.String(32),unique=True)
    password = db.Column(db.String(32))
    # db.ForeignKey('role.id') 表示外键: 表名.id
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))
    # User希望role属性,但是这个属性的定义,需要再另一个模型中定义

@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    # 删除表
    db.drop_all()
    # 创建表
    db.create_all()
    app.run(host='192.168.235.128', port=5000, debug=True)

Demonstrate one-to-many table query under ipython:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34663267/article/details/112299983