Sequelize介绍

  • 为了快捷开发,社区出现了一系列的ORM(Object Relational Mapping)类库
  • ORM的字面意思为对象关系映射,它提供了概念性的、易于理解的模型化数据的方法。通过ORM,可以降低操作数据库的成本。开发者不需要通过编写SQL脚本来操作数据库,直接通过访问对象的方式来查询、更新数据。这样做极大地提升了开发效率,降低了开发门槛。缺点也很明显,不够高效
  • 在Node.js中,一般采用Sequelize这个ORM类库来操作数据库.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('databaseName', 'userName', 'password', {host:'localhost',  // 数据库服务地址dialect: 'mysql'   // SQL语言类型
});
sequelize.authenticate().then(()=>{console.log('Connected');
}).catch(err=>{console.error('Connect failed');
})
  • 使用docker创建一个数据库.
    使用docker-compose.yml写配置文件如下:
version: '3.1'
services:mysql:image: mysqlcommand: --default-authentication-plugin=mysql_native_passwordrestart: alwaysenvironment:MTSQL_ROOT_PASSWORD: exampleports:- 3306:3306adminer:image: adminerrestart: alwaysports:- 8080:8080

使用如下命令生成docker

docker-compose up

连接数据库

const Sequelize = require('sequelize');
const sequelize = new Sequelize('数据库名称','用户名(默认:root)','密码(docker-compose.yml中设置的)', {host:'localhost',dialect: 'mysql'
});
sequelize.authenticate().then(()=>{console.log('Connected');
})
.catch(err=>{console.error('Connect failed', err);
})

定义模型

  • 常用
const Category = sequelize.define('category', {id: Sequelize.UUID,   // 定义id字段,类型为UUIDname: Sequelize.STRING    // 定义name字段,类型为String
})
  • 给模型加约束条件
const Project = sequelize.define('project', {name: {type: Sequelize.STRING,   // 定位类型为StringallowNull: false,   //不能为空unique: true   // 必须唯一,不允许重复},date: {type: Sequelize.DATE,defaultValue: Sequelize.NOW     // 设置为当前时间}
})
  • 给字段定义Getter和Setter方法:
const Custom = sequelize.define('custom', {name: {type: Sequelize.STRING,get(){const title = this.getDataValue('title');return `${this.getDataValue('name')} (${titile}) `}},title: {title: Sequelize.STRING,set (val) {this.setDataValue('title', val.toUpperCase())}}
})

查询数据

  • 查询所有
    await Product.findAll()

  • 查询name和data字段
    await Project.findAll({ attributes: ['name', 'date'] })

在使用一个库的时候,可以先把库的方法包装以下,变成自己的库

  • 在下面的栗子中,首先把Sequelize库中的API抽离出来,根据实际的业务变成自己项目的函数.通过按需的方式引入到业务中.
  • 这样做利于维护,(例如,Sequelize库变化了,不需要整个项目寻找使用到该接口的函数,或者具体改变了,重新改变接口)

栗子

  • 项目结构如下:
  • 设计Customer表的类型,如下:
  • /mysql/model/custom.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('custom', 'root', 'example', {dialect:'mysql'
});
// 定义Customer模型
const Customer = sequelize.define('customer',{id:{type: Sequelize.UUID,unique: true,primaryKey: true,allowNull: false},name: {type: Sequelize.STRING,allowNull: false},sex: {type: Sequelize.ENUM(['男','女']),allowNull: false},address:{type: Sequelize.STRING},email: {type: Sequelize.STRING,allowNull: false},phone: {type: Sequelize.STRING},country:{type: Sequelize.STRING},city: {type:Sequelize.STRING}
});
  • /mysql/db.js中,对表的功能进行加工
const { Customer } = require('./model/custom');const { Op } = require('sequelize');
async function getAllCustomers() {return Customer.findAndCountAll({attributes: ['id', 'name', 'sex', 'fulladdress'],order: [['updatedAt', 'DESC']]})
}
async function getCustomerById(id) {return Customer.findById(id);
}async function getCustomerByName(name) {return Customer.findAll({where: {name: {[Op.like]: `${name}`}}})
}async function updateCustomer(id, customer) {const item = await getCustomerById(id)if (item) {return item.update(customer);} else {throw new Error('the customer with id ${id} is not exist');}
}async function createCustomer(customer) {return Customer.create(customer);
}async function deleteCustomer(id) {const customer = await getCustomerById(id);if (customer) {return customer.destroy();}
}
  • /mysql/app.js中对对应的路由设置数据库的操作方法(路由层还未抽离出来)
const {getAllCustomers,getCustomerById,getCustomerByName,createCustomer,updateCustomer,deleteCustomer
} = require('./db');
const koa = require('koa');
const app = new koa();
const router = new require('koa-router')();
const bodyParser = require('koa-bodyparser');app.use(async (ctx, next) => {try {await next();} catch (ex) {// ctx.type = jsonMIME;ctx.body = {status: -1,message: ex.message}}
})router.get('/customer', async ctx => {const customers = await getAllCustomers();// ctx.type = jsonMIME;ctx.body = {status: 0,data: customers};
});router.get('/customer/:id', async ctx => {const customer = await getCUstomerById(ctx.params.id);// ctx.type = jsonMIME;ctx.body = {status: 0,data: customer};
});router.get('/customer/name/:name', async ctx => {const customer = await getCUstomerByName(ctx.params.name);// ctx.type = jsonMIME;ctx.body = {status: 0,data: customer};
});router.post('/customer', async ctx => {const customer = ctx.body;await createCustomer(customer);// ctx.type = jsonMIME;ctx.body = {status: 0};
});router.put('/customer/:id', async ctx => {const id = ctx.params.id;const customer = ctx.body;await updateCustomer(id, customer);// ctx.type = jsonMIME;ctx.body = {status: 0};
});router.delete('/customer/:id', async ctx => {await deleteCustomer(ctx.params.id);// ctx.type = jsonMIME;ctx.body = {stauts: 0};
});app.use(bodyParser());
app.use(router.routes());app.listen(3000, async () => {console.log('Server is running at http://localhost:3000');
})

koa --- 使用Sequelize连接mysql相关推荐

  1. sequelize连接mysql_node.js通过Sequelize 连接MySQL

    node.js通过Sequelize 连接MySQL 一.通过koa2脚手架构建项目 1.1 安装koa-generator 在终端输入: $ npm install -g koa-generator ...

  2. sequelize支持mysql版本_使用Sequelize

    访问MySQL 当我们安装好MySQL后,Node.js程序如何访问MySQL数据库呢? 访问MySQL数据库只有一种方法,就是通过网络发送SQL命令,然后,MySQL服务器执行后返回结果. 我们可以 ...

  3. egg.js连接mysql数据库遇到的问题

    最近在策划写一个博客采用前后端分离模式,前端使用vue后端使用egg.js,我也是刚开始学习egg.js,所以会将自己踩的坑都记录下来. 首先介绍下后端为什么采用egg.js吧,之前我是学习了koa2 ...

  4. nodejs mysql access denied_Node使用Sequlize连接Mysql报错:Access denied for user ‘xxx’@‘localhost’...

    前言 最近在工作中遇到问题,问题如下: Unhandled rejection SequelizeAccessDeniedError: Access denied for user 'lupeng'@ ...

  5. 前端到全栈 -- js连接MYSQL数据库

    前端到全栈–node.js连接MYSQL数据库 前置条件: 安装node环境 安装mysql数据库 这里建议使用webstorm来写js 1.创建一个文件夹(这里以server为文件夹名举例),在命令 ...

  6. 云开发连接mysql_微信小程序云开发—云函数连接MySQL

    微信小程序云开发-云函数连接MySQL 直接上干货,主要是利用微信的云函数和Sequelize 进行连接外部MySQL ,本文章主要讲述: MySQL MySQL 拉取我的代码或则创建一个新的云开发小 ...

  7. node.js + sequelize 操作 MySQL 数据库

    Node.js + Sequelize 操作 MySQL 数据库 一. Sequelize 简介 二. 基本操作 1. 连接数据库 2. 创建一张表 3. 对数据表操作 3.1 插入操作 3.2 读取 ...

  8. 服务器nodejs连接mysql_《使用nodejs连接mysql数据库》

    上边我们熟悉了如何用docker拉取远程的mysql,以及进入这个数据库然后连接.并且在命令行操作数据库,比如查看,或者操作数据库中的表. 也可以用node js操作数据库.只不过node的原生模块里 ...

  9. .net连接mysql数据_.net连接MYSQL数据库的方法及示例!

    连接MYSQL数据库的方法及示例 方法一: 使用MYSQL推出的MySQL Connector/Net is an ADO.NET driver for MySQL 该组件为MYSQL为ADO.NET ...

最新文章

  1. 网管管理的12种方法
  2. c++ hello word
  3. 利用JavaScript中的原型给对像添加方法
  4. windows下自制动画层引擎 - 放两个demo
  5. 使用Ajax的Time实现倒计时功能
  6. C++学习之路 | PTA乙级—— 1028 人口普查 (20 分)(精简)
  7. java 整数变负数_一文帮你读懂Java整数的存储原理
  8. mysql c 驱动dll_C#调用MySQL数据库(使用MySql.Data.dll连接)mysql-connector-net-6.10.4.msi
  9. tensorflow 在加载大型的embedding模型参数时,会遇到cannot be larger than 2GB
  10. jboss7的服务器开启和关闭命令
  11. 在Windows上安装Nexus
  12. MongoDB Java
  13. 产品01]-产品经理初步认知-产品经理定义/职责/分类
  14. C语言之输出孪生素数
  15. Ubuntu10.04使用HP LaserJetPro P1606dn
  16. mysql 源码阅读_mysql 源码阅读入口
  17. maven pom.xml解析、命令说明、依赖传递、继承、聚合、properties、build、依赖范围、版本仲裁、profile
  18. 算术编码的一些关键性理解
  19. 验证码之google的reCAPTCHA使用
  20. Android RecyclerView ItemDecoration 分割线

热门文章

  1. 蒙特卡罗方法求一个三维积分(论坛帮顶)
  2. J-LINK segger 驱动,MDK5.15版本,用于解决**JLink Warning: Mis-aligned memory write: Address: 0x20000000......
  3. 以下python注释代码格式正确的是_Python文件头注释的含义,你肯定不懂
  4. drbd实现mysql地热备_heartheartbeat+drbd+mysql主库热备
  5. centeros6.8 mysql_centeros7安装mysql8,以及设置root密码
  6. sql执行有时候快有时候慢_如何让你的 SQL 执行的飞起?
  7. html json解析插件,jQuery插件jsonview展示json数据
  8. 应用内安装部分手机出现解析错误
  9. ONENET读取与控制麒麟座MINI开发板LED状态
  10. Linux 系统常用命令汇总(二) vi 文本编辑