Sequelize 使用教程

Sequelize 使用教程

- 简介

Sequelize 是一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能。

- 快速入门

1. 导入Sequelize的包文件

在项目路径下输入 npm i -S sequelize ,稍等片刻
在这里插入图片描述

2. 导入你的数据库的驱动包(这里以Mysql为例)

在项目路径下数据 npm i -S mysql2,稍等片刻
在这里插入图片描述

3. 创建数据库连接模型

新建一个文件名为MysqlConnection的js文件,详细代码解释看注释

const { Sequelize } = require('sequelize');

// 第一个参数:连接的数据库名
// 第二个参数:数据库的用户名
// 第三个参数:数据库的密码
const mysql = new Sequelize('mytest', 'root', 'root', {
    dialect: 'mysql',       // 这里可以改成任意一种关系型数据库
    host: 'localhost',      // 数据库服务器
    timezone: '+08:00',     // 这里是东八区,默认为0时区
    pool: {                 // 使用连接池
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000,
    },
});

// 测试连接是否成功
(async () => {
    try {
        await mysql.authenticate();
        console.log('Connection has been established successfully.');
    } catch (error) {
        console.error('Unable to connect to the database:', error);
    }
})();   // 多一个括号表示调用方法

使用 node MysqlConnection.js来执行一下文件
在这里插入图片描述

数据库连接成功,将连接测试注释掉,并在下面将mysql对象暴露

tip:如果你不理解为什么用module.exports来暴露对象的话,你可以参看这篇文章来帮助你的理解 https://blog.csdn.net/interestANd/article/details/119058481

// 将连接对象暴露出去
module.exports = mysql;
4. 新建数据库模型(类似于Java的pojo类)

这里举例新建一个BookModel.js

const { DataTypes } = require('sequelize')
// 将数据库连接对象导入
const sequelize = require('./MysqlConnection')

// 测试代码 导入对象成功
// console.log(sequelize);

// 创建模型
const Book = sequelize.define('book', {
    /** 书名 */
    name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    /** 价格 */
    price: DataTypes.INTEGER,
    /** 作者 */
    author: DataTypes.STRING,
    /** 类型 */
    type: DataTypes.STRING
});

// 导出模型
module.exports = Book;

5. 模型准备就绪,开始测试添加数据

注意:第一次运行时,要同步数据库中的表,推荐使用 sync(),可以参考下面中被注释掉的代码

  • 可以使用build + save 来实现插入数据库
const Book = require('./BookModel');

// 使用 build 新建一个BookModel对象
const comicBook = Book.build({
    name: 'Rick And Morty - The fifth season',
    price: 20,
    author: 'unknow',
    type: 'comic'
});     // 注意后面有 ( { 开头的一定要写 ; !


// 保存
(async () => {
    try {
        // 第一次运行要同步数据库,若没有这个数据库则新建,有则检查表结构与model是否一致,使用sync()当不一致时不作任何更改,不存在破坏性
        // await Book.sync();
        await comicBook.save();
        console.log("保存成功");
    } catch(error) {
        console.log("操作失败!\n"+error)
    }
})();

运行结果:
在这里插入图片描述
在这里插入图片描述
可以看到,操作成功,但是多了 idcreatedAtupdateAt 三个字段。当我们不手动设置主键时,Sequelize 会自动为我们添加一个 id 的字段作为主键,而Sequelize 使用数据类型 DataTypes.DATE 自动向每个模型添加 createdAtupdatedAt 字段。

  • Sequelize提供了 create方法,该方法将上述的 build 方法和 save 方法合并为一个方法
const Book = require('./BookModel');

// create方法:将 build 与 save 合二为一
(async () => {
    await Book.create({
        name: 'Rick And Morty - The first season',
        price: 30,
        author: 'unkwon',
        type: 'comic'
    }).then(() => {
        console.log("操作成功");
    }).catch(error => {
        console.log("操作失败!\n" + error);
    })
})();

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

  • Sequelize 还提供了批量创建和插入多个实例:bulkCreate传入一个数据即可实现批量创建插入
const Book = require('./BookModel');

async function saveMany(books) {
    try {
        await Book.bulkCreate(books);
        console.log("操作成功!");
    } catch(error) {
        console.log("操作失败!\n"+ error);
    }
}

var books = [
    {name: 'book6'},
    {name: 'book7'},
    {name: 'book8'},
    {name: 'book9'},
    {name: 'book10'},
]
saveMany(books);

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

6. 查询数据
  • findAll() 读取全部字段、所有数据
const Book = require('./BookModel');

async function findAllBooks() {
    try {
        const books = await Book.findAll();
        console.log("All Books:", JSON.stringify(books, null, 2));
    } catch(error) {
        console.log("操作失败!\n" + error);
    }
}

findAllBooks();

**运行结果:**将所有的字段、数据都获得

在这里插入图片描述

  • findAll() 读取部分字段的所有数据
const Book = require('./BookModel');

async function findAllBooks() {
    try {
        const books = await Book.findAll({
            // select 'name', 'author', 'type' from books
            attributes: ['name', 'author', 'type']
        });
        console.log("All Books:", JSON.stringify(books, null, 2));
    } catch (error) {
        console.log("操作失败!\n" + error);
    }
}

findAllBooks();

运行结果: 只获得筛选过后的结果
在这里插入图片描述

  • findAll() 条件筛选查询 where
const Book = require('./BookModel');
const { Op } = require('sequelize')

// 通过id查询
async function findBooksById(id) {
    const books = await Book.findAll({
        // select 'name', 'author', 'type' from books
        attributes: ['name', 'author', 'type'],
        where: {
            id: id
        }
    });
    console.log("id 为 "+id+"的book:", JSON.stringify(books, null, 2));
}

findBooksById(3);

// 模糊查询
async function findBooksByNameLike() {
    const books = await Book.findAll({
        where: {
            name: { [Op.like]: '%Rick%' }
        }
    })
    console.log("All books which name like Rick:", JSON.stringify(books, null, 2));
}
findBooksByNameLike();

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

7. 更新数据:update
  • update 可以使用 where 来进行筛选
const Book = require('./BookModel');

async function updateById(id) {
    const res = await Book.update({ price: "199"}, {
        where: {
            id: id
        }
    })
    console.log(res)    // [ 1 ]
}

// 更改 id 为 10 的书的价格
updateById(10);

运行结果:
在这里插入图片描述
这里的 [ 1 ] 是表示成功更新了的数据数量。你查询到,但是没修改成功也不算;查询不到也是不算。

8. 删除数据:destroy
  • 通过 id 删除数据

    const Book = require('./BookModel');
    
    // async function addBookToDelete() {
    //     book = Book.create({
    //         name: 'i love nodejs',
    //         author: 'unknow',
    //         price: 1999999
    //     });
    // }
    // addBookToDelete();
    
    async function deleteById(id) {
        await Book.destroy({
            where: {
                id: id
            }
        })
    }
    deleteById(5);
    

    **运行结果:**删除成功,查找结果为空

在这里插入图片描述

9. 托管事务

托管事务会自动处理提交或回滚事务。

  • 通过将回调传递给 sequelize.transaction 来启动托管事务
const sequelize = require('./MysqlConnection')
// const t = await sequelize.transaction();

const Book = require('./BookModel');

async function addBook() {
    try {
        const result = await sequelize.transaction(async (t) => {
            const book = await Book.create({
                name: 'testTransaction',
            }, { transaction: t });
            throw new Error();
            return book;    // 如果执行到此行,则表示事务已成功提交,`result`是事务返回的结果,这种情况下,result 中的数据就是 user
        });

    } catch (error) {
        console.log("数据回滚\n" + error);
    }
}
// 执行 addBook() 方法
addBook();

运行结果:
第一种:出现异常时,数据回滚 ,没有插入到数据库中
在这里插入图片描述

第二种:将上面的抛出异常代码注释,正常提交事务
在这里插入图片描述
在这里插入图片描述

  • 9
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值