初识sequelize

  1. 1. sequelize是一个数据的工具,ORM数据库工具
  2. 2. ORM:对象关系映射,面向对象的方式去操作数据库
  3. 3. 基于promise
  4. 4. 还要安装跟数据库相关的驱动,mysql2(支持promise)
  5. 5. npm i sequelize mysql2 --save (npm i sequelize@5.3.0 mysql2@1.5.3 --save)
  6. 6. 连接数据库

连接数据库

  1. // 连接数据库
  2. const { Sequelize } = require('sequelize')
  3. // import * as tedious from 'tedious'
  4. const tedious = require('tedious')
  5. const { MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PWD, MYSQL_DB } = require('../config/config.default')
  6. const seq = new Sequelize(MYSQL_DB, MYSQL_USER, MYSQL_PWD, {
  7. host: MYSQL_HOST,
  8. dialect: 'mysql',
  9. port: MYSQL_PORT
  10. // dialectModule: tedious
  11. })
  12. // 测试连接
  13. // seq.authenticate().then(() => {
  14. // console.log('数据库连接成功')
  15. // }).catch((err) => {
  16. // console.log('数据库连接失败', err)
  17. // throw err
  18. // })
  19. module.exports = seq

创建表

  1. const { DataTypes } = require('sequelize')
  2. const seq = require('../db/seq')
  3. // 创建模型
  4. // 模型名称 zd_user ==> zd_users 表名
  5. const User = seq.define('zd_user', {
  6. // 模型顺序 => 表的字段
  7. // id 会自动创建,主键,自增
  8. user_name: {
  9. type: DataTypes.STRING,
  10. allowNull: false, // 这个字段不允许为空
  11. unique: true,
  12. comment: '用户名, 唯一'
  13. },
  14. password: {
  15. type: DataTypes.CHAR(64),
  16. allowNull: false,
  17. comment: '密码'
  18. },
  19. is_admin: {
  20. type: DataTypes.BOOLEAN,
  21. allowNull: false,
  22. defaultValue: 0, // 0: 普通用户 1: 管理员
  23. comment: '是否为管理员, 0: 普通用户(默认) 1: 管理员'
  24. }
  25. }, {
  26. // 这个字段表示创建表的时候不会自动创建 createAt, updateAt
  27. // createAt, updateAt 表示这条记录的创建时间和更新时间
  28. // timestamps: false
  29. })
  30. // 同步到数据库
  31. // 已经存在,先删除,在重新创建
  32. // 如果不设置 force: true 那么如果存在这张表了,就不会创建了
  33. // User.sync({ force: true })