全栈项目|小书架|服务器开发-NodeJS 中使用 Sequelize 操作 MySQL数据库

时间:2022-05-16 02:47:50

安装

官网:https://sequelize.org/v5/manual/getting-started.html

安装sequelize及数据库连接驱动

npm install --save sequelize
$ npm install --save mysql2

使用

创建连接:

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

创建Model表:

const Model = Sequelize.Model;
class User extends Model {}
User.init({
  // attributes
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  lastName: {
    type: Sequelize.STRING
    // allowNull defaults to true
  }
}, {
  sequelize,
  modelName: 'user'
  // options
});

生产数据:

// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
  // Now the `users` table in the database corresponds to the model definition
  return User.create({
    firstName: 'John',
    lastName: 'Hancock'
  });
});

增加数据

// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {
  console.log("Jane's auto-generated ID:", jane.id);
});

删除数据

// Delete everyone named "Jane"
User.destroy({
  where: {
    firstName: "Jane"
  }
}).then(() => {
  console.log("Done");
});

改变数据

// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" }, {
  where: {
    lastName: null
  }
}).then(() => {
  console.log("Done");
});

查询数据

// Find all users
User.findAll().then(users => {
  console.log("All users:", JSON.stringify(users, null, 4));
});

数据类型

https://sequelize.org/v5/manual/data-types.html

Model 使用

https://sequelize.org/v5/manual/models-usage.html

Model 查询

https://sequelize.org/v5/manual/querying.html

数据迁移

https://sequelize.org/v5/manual/migrations.html

对于数据迁移这块,笔者目前实际使用还是不熟练,比如 model添加了新的字段如何处理、开发环境和生产环境新添加字段或者删除字段怎么处理 ,希望有熟悉的朋友能够指导一二,不胜感激。

参考1:Sequelize 和 MySQL 对照
参考2:Getting started-Sequelize

咨询请加微信:轻撩即可。
全栈项目|小书架|服务器开发-NodeJS 中使用 Sequelize 操作 MySQL数据库