Database processing
_ORM overview
- Explanation: Object-relational mapping model
- Features:
- Map class names and attributes to database table names and fields
- The object of the class will be mapped to the data row by row in the database table
- Advantages and disadvantages:
- advantage
- No longer need to write SQL statements
- No longer care about what database is used
- Disadvantage
- Since the database is not operated directly through SQL, there is a performance loss
- advantage
_ORM operation process
- Operating procedures
-
Install extension
pip install flask_sqlalchemy pip install flask_mysqldb/pymysql
-
Set the configuration information of the database
-
Create sqlalchemy object db, associate app
-
Write model classes and fields, inherited from db.Model
-
Operating database
增删改 查询
-
Example:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# 2.设置数据库的配置信息
# app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://数据库账户:密码@ip和端口/数据库名称",如果安装的是flask_mysqldb,则只需要mysql://
# 设置数据库的链接信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/data36"
# 该字段增加了大量的开销,会被禁用,建议设置为False
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# 3.创建sqlalchemy对象db,关联app
db = SQLAlchemy(app)
# 4. 编写模型类和字段,继承自db.Model
class Student(db.Model):
# 主键,参数1:表示id的类型,参数2:表示id的约束类型
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32))
@app.route('/')
def hello_world():
return "hello world"
if __name__ == '__main__':
# 删除继承自db.Model的表
# db.drop_all()
# 5.创建数据库的表,创建的是继承自db.Model的表
db.create_all()
app.run(debug=True)
ORM operation attention
- important point:
-
Because sqlAlchemy goes to app to read the configuration information, it needs to be set to app.config
-
Database link information
-如果安装的是flask_mysqldb,那么链接信息:mysql://<用户名>:<密码>@<IP地址>:<端口号>/<数据库名字> -如果安装的是pymysql,那么链接信息:mysql+pymysql://<用户名>:<密码>@<IP地址>:<端口号>/<数据库名字>
-
The written model class must inherit from db.Model to be mapped
-
If you do not specify the table name, the default is the lowercase of the model class. If you need to specify the table name yourself, use __tablename__ ='table name'
-
ORM cannot generate a database when mapping
-
Addition, deletion and modification of database
- Additions and deletions
-
All use db.session operation
-
Common methods:
-db.session.add(obj):添加单个对象 -db.session.add_all([obj1,obj2]):添加多个对象 -db.session.delete(obj):删除单个对象 -db.session.commit():提交会话 -db.drop_all():删除继承自db.Model所有表 -db.create_all():创建继承自db.Model所有表 其他方法: -db.session.rollback():回滚 -db.session.remove():移除会话 注意点: -如果想要打印一个对象的时候看到指定的信息,那么重写__repr__ 方法
-
Basic database query
- All are done through model class .query
Basic use
数据库增加,删除,修改操作:
增加:
user = User(name='laowang')
db.session.add(user)
db.session.commit()
修改:
user.name = 'xiaohua'
db.session.commit()
删除:
db.session.delete(user)
db.session.commit()
以下12条查询语句:
特点:
模型.query: 得到了所有模型的数据的结果集对象
模型.query.过滤器: 过滤出了想要的数据,还是一个查询结果集对象
模型.query.过滤器.执行器: 取出了结果集中的内容
查询所有用户数据
User.query.all() ==> [user1,user2]
查询有多少个用户
User.query.count()
查询第1个用户
User.query.all()[0]
查询id为4的用户[3种方式]
User.query.get(4)
User.query.filter_by(id = 4).first()
User.query.filter(User.id == 4).first()
查询名字结尾字符为g的所有数据[开始/包含]
User.query.filter(User.name.endswith('g')).all()
User.query.filter(User.name.startswith('g')).all()
User.query.filter(User.name.contains('g')).all()
查询名字不等于wang的所有数据[2种方式]
查询名字和邮箱都以 li 开头的所有数据[2种方式]
User.query.filter(User.name.startswith('li'),User.email.startswith('li')).all()
User.query.filter(and_(User.name.startswith('li'),User.email.startswith('li'))).all()
查询password是 `123456` 或者 `email` 以 `itheima.com` 结尾的所有数据
User.query.filter(or_(User.password == '123456',User.email.endswith('itheima.com'))).all()
查询id为 [1, 3, 5, 7, 9] 的用户列表
User.query.filter(User.id.in_([1,3,5,7,9])).all()
查询name为liu的角色数据
user = User.query.filter(User.name == 'liu').first()
role = Role.query.filter(Role.id == user.role_id).first()
查询所有用户数据,并以邮箱排序
User.query.order_by(User.email).all()
User.query.order_by(User.email.desc()).all()
每页3个,查询第2页的数据
paginate = User.query.paginate(page, per_page,Error_out)
paginate = User.query.paginate(2,3,False)
page: 哪一个页
per_page: 每页多少条数据
Error_out: False 查不到不报错
paginate .pages: 共有多少页
paginate .items: 当前页数的所有对象
paginate .page: 当前页
Database relation query relationship
-
Explanation: In order to facilitate database related queries
-
Features:
- Will not generate entity fields in the database
- Relationship attributes, need to be added on one side
-
format:
Users = db.relationship("多方的模型类")
-
Use format:
role = Role.query.get(1) users = role.users
Database reverse query backref
- Explanation: If you know the user, can you quickly find out which user plays which role?
-
Original query method:
user = User.query.get(1) role = Role.querye.filter(Role.id == user.role_id).first()
-
Quick Search:
-
Use backref to add reverse attributes, you can quickly query
-
format:
users = db.relationship("多方的模型类",backref="role")
-
Quick Search:
user = User.query.get(1) role = user.role
-
Database lazy query lazy
-
Explanation: Once relationship and backref are used, the system will automatically do sub-queries
- Subquery (subquery): If one party is queried, the related party will be queried automatically
- Dynamic query (dynamic): query only when it is used
-
lazy use
db.relationship("多方的模型类",backref="role",lazy="dynamic")