• 【ORM框架:Sequelize的查询】


    一、ORM(Object Relational Mapping,对象关系映射)

    1、持久化

    持久化 :将内存中的对象保存到磁盘的数据库中或其他文件中

    2、对象关系映射:

    类的属性表的列
    类的对象表的行

    在js程序中对对象的操作,就是操作了数据库表的行.

    3、ORM框架:Sequelize

    (1)安装模块:

    npm install mysql2
    npm install sequelize

    (2)创建数据库连接的配置对象

    创建数据库连接的配置对象:使用sequelize完成相关配置

    (3)使用sequelize建立模型(类)

    使用sequelize建立模型(类),该模型实现与数据表的orm映射

    (4)使用模型进行crud操作(增删改查)

    方法说明
    模型名.findAll()查询所有
    模型名.findOne()带条件查询
    模型名.create()插入数据
    模型名.destory()删除数据
    模型名.update()更新数据

    ①查询所有

    seqconfig.js后端配置文件:

    //1、导入sequelize模块,引入框架
    const Sequelize = require('sequelize')
    
    //2、配置数据库连接对象
    const mysqlDemo = new Sequelize('xy','root','123456',{
        host:'localhost',
        port:3306,
        dialect:'mysql',//数据库方言,类型
        pool:{//数据库连接池
            max:10,
            min:3,
            idle:100000
        }
    })
    //3、导出数据库连接的配置对象
     module.exports = mysqlDemo
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    Student.js映射数据库关系表的代码如下:

    //1、导入sequelize模块
    const Sequelize = require('sequelize')
    
    //2、导入配置文件
    const mysqlDemo =require('../seqconfig')
    
    //3、创建数据类型(模型)
    const Student = mysqlDemo.define('stu',{
        Id:{
            type:Sequelize.STRING,//数据类型
            primaryKey:true,//主键
            field:'sid'
        },
        Name:{
            type:Sequelize.STRING,
            field:'sname',
            allowNull:false//该列不能为空(false),true表示可以为空
        },
        Age:{
            type:Sequelize.INTEGER,
            field:'age',
            allowNull:false//该列不能为空(false),true表示可以为空
        },
        Gender:{
            type:Sequelize.STRING,
            field:'gender',
            allowNull:false//该列不能为空(false),true表示可以为空
         }
         },
        {
        freezeTableName:true,//true表示应用用户自己的表名,false(默认)表示sequelize定义表名(就是模型名后面加s:Students)
            timestamps:false//默认为true(会给表添加时间戳列,创建表的时间戳,更新表的时间戳两列),false表示不添加时间戳列。
       })
    
    module.exports = Student//导出这个数据库模型(表)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    sequecrud.js路由接口文件代码如下:

    const express = require('express')
    const sequelize = require('sequelize')
    const router = express.Router()
    const Student =require('../config/model/Student')
    
    //测试Sequelize模块
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    module.exports=router
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    app.js配置代码:

    var seqRouter=require('./routes/sequecrud')
    app.use('/sequelize',seqRouter);
    
    • 1
    • 2

    运行结果如下:

    测试结果如下(查询全部数据):
    在这里插入图片描述在这里插入图片描述

    ②带条件查询

    只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //http://localhost:3000/sequelize/findone
    router.get('/findone',(req, res) => {
        Student.findOne({
            where:{
                Id:'S_1013'
            }
        }).then((data)=>{
            res.send(data)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    运行结果如下:
    测试结果如下:
    在这里插入图片描述正如下图证明可得,查询结果正确。
    在这里插入图片描述

    ③插入数据

    只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //http://localhost:3000/sequelize/add
    router.get('/add',(req, res) => {
        Student.create({
            Id:'S_1012',
            Name:'小王',
            Age:'21',
            Gender:'男'
        }).then((data)=>{
            res.send(data)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    运行结果如下:
    测试结果如下:
    在这里插入图片描述
    如下图查询数据库表知,插入数据成功:

    在这里插入图片描述

    ④删除数据

    只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //http://localhost:3000/sequelize/delete
    router.get('/delete',(req, res) => {
        Student.destroy({
            where:{
                Id:'S_1012'
            }
        }).then((data)=>{
            res.send(data)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    运行结果如下:
    数据已被删除如下图所示:
    在这里插入图片描述

    ⑤更新数据

    只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //http://localhost:3000/sequelize/update
    router.get('/update',(req, res) => {
        Student.findOne({
            where:{
                Id:'s_1007'
            }
        }).then((Student)=>{
            Student.update({
               Name:'更新后',
                Age:16,
                Gender:'男'
            }).then((data)=>{
                res.send(data)
            })
        })
    
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    运行结果如下:

    在这里插入图片描述
    更新结果应如红框所示:
    在这里插入图片描述测试结果:
    在这里插入图片描述

    (5)只查询部分字段

    例如:select sname from stu;的实现方式

    也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
           attributes:['sname','sid'],//查询部分字段
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    运行结果:
    在这里插入图片描述

    (6)使用聚合函数:count()、sum()、avg()、max()、min()

    attributes:[[sequelize.fn(‘count’,sequelize.col(‘sid’)),‘记录总数’]],

    也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
            attributes:[[sequelize.fn('count',sequelize.col('sid')),'记录总数']],
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    运行结果:
    在这里插入图片描述

    (7)查询操作符的使用:需要导入Sequelize模块的Op子模块

    也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    const Op =sequelize.Op
    //测试Sequelize模块
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
           // attributes:['sname','sid'],//查询部分字段
           //  attributes:[[sequelize.fn('count',sequelize.col('sid')),'记录总数']],
            where : {
                sname: {
                    [Op.like]: '李%'
                }
            },
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    查询结果应如红框所示:
    在这里插入图片描述

    测试结果:
    在这里插入图片描述也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    const Op =sequelize.Op
    //测试Sequelize模块
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
           // attributes:['sname','sid'],//查询部分字段
           //  attributes:[[sequelize.fn('count',sequelize.col('sid')),'记录总数']],
            where : {
                age:{
                    [Op.in]:[15,22]
                  }
              },
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    查询结果应如红框所示:

    在这里插入图片描述

    测试结果:
    在这里插入图片描述
    也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    const Op =sequelize.Op
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
            where : {
                age:{
                    [Op.between]:[15,22]
                }
            },
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    查询结果应如红框所示:
    在这里插入图片描述

    测试结果:
    在这里插入图片描述

    (8)使用and 和 or谓词进行查询

    也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    const Op =sequelize.Op
    //测试Sequelize模块
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
            where : {
                [Op.and]:[
                    {
                        sname:{
                            [Op.like]:'李%'
                        }
                    },
                    {
                        age:{
                            [Op.eq]:22
                        }
                    }
                ]
           },
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    查询结果应如红框所示:

    在这里插入图片描述

    测试结果:

    在这里插入图片描述

    (9)对查询结果进行排序:使用order子句

    也只修改sequecrud.js路由接口文件关键代码,其余代码同上:

    //测试Sequelize模块
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
            order:[
                ['age','desc']
            ],
           
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    测试结果:
    在这里插入图片描述

    (10)使用limit进行查询

    //测试Sequelize模块
    //http://localhost:3000/sequelize/seq
    router.get('/seq',(req, res) => {
        Student.findAll({
            limit:2,
            offset:3,
            raw:true//目的是不显示时间戳
        }).then(function(result){
            res.send(result)
        })
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    查询结果应如红框所示:
    在这里插入图片描述

    测试结果:

    在这里插入图片描述

  • 相关阅读:
    Keras CIFAR-10分类 LeNet-5篇
    Spring6--IOC反转控制 / 基于XML管理bean
    JS 常见报错及异常处理办法总结
    6 分钟看完 BGP 协议。
    【Docker部署私服仓库Harbor详细教程步骤&镜像拉取&推送到Harbor仓库实战演练应用】
    Yii 知识点总结
    Bus:消息总线
    React路由
    【Vue】用Vue代码详细介绍computed计算属性的用法
    猿创征文|【JavaSE】 Collection集合全家桶
  • 原文地址:https://blog.csdn.net/m0_46839072/article/details/126044776