sequelize模块的使用

一、sequelize模块的使用

模块简介:Sequelize是一个用于Node.js 的非常优秀的ORM框架, 支持MySQL等多种关系型数据库。

1.ORM:对象关系映射。sequelize是实现了ORM思想的一个模块。
映射关系:

  • 类-----表

  • ​ 属性----列​

  • 对象----行(元组)

2.使用过程:
(1)导入sequelize模块(首先要安装该模块)

npm install sequelize

(2)创建sequelize的对象

 const MySequelize = new Sequelize('数据库名','用户名','密码',{
	      host: '数据库服务器',
		  port: 端口号,
		  dialect:'数据库类型',
		  pool: {
		     max: '最大连接对象数',
			 min: '最少的连接对象数',
			 idle: '最长等待时间'
		  }
	   });

(3)创建数据模型
示例代码:

const Sequelize = require('sequelize');
const MySequelize = require('../config/dbconfig');

var ClassModel = MySequelize.define('classes',{
   cNo: {
       type: Sequelize.INTEGER,
       field: 'cno',
       primaryKey: true,
       autoIncrement: true
   },
   cName: {
       type: Sequelize.STRING(30),
       field: 'cname',
       allowNull: false
   },
   cAddress: {
       type: Sequelize.STRING(50),
       field: 'caddress',
       allowNull: false
   }
},
   {
       freezeTableName: true, //使用用户给定的表名
       timestamps: false
   });

module.exports = ClassModel;

(4)进行CRUD操作

​ A、插入数据:

模型名.create({

    属性名1:值1,

    ......

}).then(result=>{

    插入成功后的代码;    //参数result中存放的是插入成功的数据

}).catch(error=>{

    插入失败后的代码;  //参数error中存放的是插入失败的信息

})

​ B、删除数据:

模型名.destroy({

    where:{

        属性名:值

    }

}).then(result=>{

    删除成功后的代码;    //参数result中存放的是删除的记录数(行数)

}).catch(error=>{

    删除失败的处理代码;  //参数error中存放的是删除失败的信息

})

​ C、更新数据:

模型名.findOne({
    where:{
        属性名:}
}).then(result=>{   //result中放的是查找到的数据
    result.update({
        属性名1:1,
        属性名2:2
	}).then(data=>{  //data中放的是更新后的数据
        处理代码
    }).catch(err=>{
        处理代码
    })
}).catch(error=>{
    未查到记录的处理代码
})

​ D、查询数据

模型名.findAll({
    where:{
        属性名:}
}).then(result=>{ //result中存放查询到的数据
    处理代码
})

3.多种查询方法

(1)只查询部分列

//查询部分字段
UserModel.findAll({
    attributes:['s_name','s_address'],
    raw:true
}).then(result=>{
    console.log(result);
}).catch(err=>{
    console.log(err);
})

(2)聚合函数

//聚合函数
UserModel.findAll({
    attributes:[[Sequelize.fn('count',Sequelize.col('s_id')),'记录总数']],
    raw:true
}).then(result=>{
    console.log(result);
})

(3)模糊查询:需要引入sequelize模块中的子模块(包含查询用的操作符)

//模糊查询
EmployeeModel.findAll({
    where:{
        sname:{
            [Op.like]:'李%'
        }
    },
    raw:true
}).then(data=>{
    console.log(data);
})

(4)between查询:

//between使用
EmployeeModel.findAll({
    where:{
        age:{
            [Op.between]:[20,30]  //查询年龄在20-30之间的用户数据
        }
    },
    raw:true
}).then(data=>{
    console.log(data);
})

(5)排序

//查询地址是西安或者北京的数据
EmployeeModel.findAll({
    where:{
        saddress:{
            [Op.in]:['西安','北京']
        }
    },
    order:[
        ['age','desc']  //查询结果按年龄降序排列
    ],
    raw:true
}).then(data=>{
    console.log(data);
})

(6)and,or的使用

//and使用
EmployeeModel.findAll({
    where:{
        [Op.and]:[
            {
                sgender:{
                    [Op.eq]:'男'
                }
            },
            {
                saddress:{
                    [Op.eq]:'西安'
                }
            }
        ]
    },
    raw:true
}).then(data=>{
    console.log(data)
});

//or的使用
EmployeeModel.findAll({
    where:{
        [Op.or]:[
            {
                sgender:{
                    [Op.eq]:'男'
                }
            },
            {
                saddress:{
                    [Op.eq]:'西安'
                }
            }
        ]
    },
    raw:true
}).then(data=>{
    console.log(data)
});

(7)分页查询

//分页查询:limit、offset
EmployeeModel.findAll({
    limit:3,  //查询的记录数
    offset:1,  //查询起始位置  索引从0开始
    raw:true
}).then(data=>{
    console.log(data);
})
二、sequelize实现多表连接查询

1.一对多

​ 班级—学生(一个班级有多名学生,一个学生只能属于一个班级)

​ 关联设计方法:

	'一'端:班级
	
​	 '多'端:学生

​	 '一'端不变,'多'端增加一列作为外键连接'一'端的主键

2.sequelize:
(1)安装模块:npm install sequelize

(2)导入模块:const Sequelize = require(‘sequelize’);

(3)创建Sequelize类的实例对象

 const MySequelize = new Sequelize('数据库名','用户名','密码',{
	      host: '数据库服务器',
		  port: 端口号,
		  dialect:'数据库类型',
		  pool: {
		     max: 最大连接对象数,
			 min: 最少的连接对象数,
			 idle: 最长等待时间
		  }
	   });
	   
	   module.exports = MySequelize;

(4)利用Sequelize类的实例对象定义数据模型

模型名 = MySequelize.define('表名',{属性定义},{表名设置,时间戳设置})

3.使用sequelize模块的目的

(1)提高了开发效率

(2)不用写SQL语句:用户只需要调用模块提供的相关方法

(3)实现了ORM思想

三、小结

1.在操作关系型数据库时,一般我们都会选择一个ORM框架,以封装复杂的业务逻辑,用面向对象的方式来操作数据表,替代直接的SQL操作。
2.sequelize模块是一个好用的优秀的ORM模型框架,它可以支持多种关系型数据库,便于我们操作数据库。
3.

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sequelize是一个Node.js ORM模块,可以方便地连接多种关系型数据库。下面是使用Sequelize连接数据库的基本步骤: 1. 安装Sequelize模块: ``` npm install sequelize ``` 2. 导入Sequelize模块: ``` const Sequelize = require('sequelize'); ``` 3. 创建一个Sequelize实例: ``` const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql' }); ``` 其中,database、username、password分别是你的数据库名称、用户名和密码,host是数据库的地址,dialect是数据库类型。 4. 测试连接是否成功: ``` sequelize.authenticate() .then(() => { console.log('Connection has been established successfully.'); }) .catch(err => { console.error('Unable to connect to the database:', err); }); ``` 如果连接成功,会输出“Connection has been established successfully.”,否则会输出错误信息。 5. 定义模型(可选): ``` const User = sequelize.define('user', { firstName: { type: Sequelize.STRING, allowNull: false }, lastName: { type: Sequelize.STRING } }); User.sync({ force: true }) .then(() => { console.log('User table created successfully.'); }) .catch(err => { console.error('Unable to create user table:', err); }); ``` 其中,User是模型名称,user是表名,firstName和lastName是表的字段名,Sequelize.STRING表示字段类型为字符串,allowNull表示是否允许为空。sync方法用来同步模型和数据库,force: true表示每次同步时都会先删除原有表再创建新表。 以上就是使用Sequelize连接数据库的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值