Sequelize与mysql的基础使用,增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qmzmzxk/article/details/82109582

Sequelize和mysql的基础使用,增删改查

​ 在接触sequelize之前,一直使用最简易mysql pool方式连接数据库,对于数据库的操作是拼接sql的方式。拼接sql的方式在小型项目中能够适用。但当项目变得复杂的时候,拼接sql的方式就变得不太方便,代码的维护量变大,需求改动会导致大量代码的重写。

安装Sequelize环境

​ 使用npm安装Sequelize环境

$ npm install --save sequelize

# 安装下面的其中之一,本次安装的是msysql2
$ npm install --save pg pg-hstore
$ npm install --save mysql2
$ npm install --save sqlite3
$ npm install --save tedious // MSSQL

数据库连接

​ Sequelize将在初始化时设置连接池,所以如果从单个进程连接到数据库,你最好每个数据库只创建一个实例。 如果要从多个进程连接到数据库,则必须为每个进程创建一个实例,但每个实例应具有“最大连接池大小除以实例数”的最大连接池大小。 因此,如果您希望最大连接池大小为90,并且有3个工作进程,则每个进程的实例应具有30的最大连接池大小。

var sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'|'sqlite'|'postgres'|'mssql',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite'
});

// Or you can simply use a connection uri
var sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname');

测试连接

​ 我们可以使用 .authenticate() 测试连接是否成功。

sequelize
  .authenticate()
  .then(function(err) {
    console.log('Connection has been established successfully.');
  })
  .catch(function (err) {
    console.log('Unable to connect to the database:', err);
  });

Sequelize 模板

​ 模板需要设置一下三个函数 sequelize.define('name', {attributes}, {options}).以下是官方文档的例子

var User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING
  },
  lastName: {
    type: Sequelize.STRING
  }
});

// force: true 如果表已经存在,将会把表丢弃
User.sync({force: true}).then(function () {
  // 表已经创建
  return User.create({
    firstName: 'John',
    lastName: 'Hancock'
  });
}); 

​ 以下为使用例子:

   const history = sequelize.define(
    'history',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true
      },
      dt: DataTypes.STRING,
      username: DataTypes.STRING,
      mail: DataTypes.STRING,
    },
    {
      timestamps: false,
      underscored: true,
      freezeTableName: true,
      // define the table's name
      tableName: 'history'
    }
  )

查询

​ 下面可以开始最简单的查询操作。查询分为全部查询数据,根据条件查询,全部查询数据及条数(分页),查询特一数据。

  • 查询全部数据

    history.findAll().then(function(history) {
    console.log(history)
    })
  • 根据条件查询数据

    其中OP.or的意思是满足下面dt和name的任意一个都可以,不需要全部满足。这个Op是使用以下语句引人入才能够使用,在很多博客里都没有写明,需要查看官方博客才明了const Op = sequelize.Op;

    let data = await history.findAll({
    where:{
      [Op.or]: [
        {
          dt:{
            [Op.like]: `%${crb.dt}%`
          }
        },
        {
          name:{
            [Op.like]: `%${crb.name}%`
          }
        }
      ]
    }
    });

    搜索有多个条件可以供使用:

    扫描二维码关注公众号,回复: 2991656 查看本文章
    $and: {a: 5}           // AND (a = 5)
    $or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)
    $gt: 6,                // > 6
    $gte: 6,               // >= 6
    $lt: 10,               // < 10
    $lte: 10,              // <= 10
    $ne: 20,               // != 20
    $eq: 3,                // = 3
    $not: true,            // IS NOT TRUE
    $between: [6, 10],     // BETWEEN 6 AND 10
    $notBetween: [11, 15], // NOT BETWEEN 11 AND 15
    $in: [1, 2],           // IN [1, 2]
    $notIn: [1, 2],        // NOT IN [1, 2]
    $like: '%hat',         // LIKE '%hat'
    $notLike: '%hat'       // NOT LIKE '%hat'
    $iLike: '%hat'         // ILIKE '%hat' (case insensitive) (PG only)
    $notILike: '%hat'      // NOT ILIKE '%hat'  (PG only)
    $like: { $any: ['cat', 'hat']}
                         // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
    $overlap: [1, 2]       // && [1, 2] (PG array overlap operator)
    $contains: [1, 2]      // @> [1, 2] (PG array contains operator)
    $contained: [1, 2]     // <@ [1, 2] (PG array contained by operator)
    $any: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)
    
    $col: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example
  • 根据条件查询数据及条数(分页使用)

    下面这个语句查询出来的数据包含了数据总条数,可以用来设置分页。offset是便宜数,limit为每页数量

    let data = await B.m.db.history.findAndCountAll({
    where:{
      name:{
        [Op.like]:`%${crb.name}%`
      },
      status:{
        [Op.in]:crb.status
      }
    },
    order:[
      ['id',crb.sort]
    ],
    offset: (crb.currPage - 1) * (crb.pageSize),
    limit: crb.pageSize,
    });
  • 查询特定数据

    根据id获得特定的数据。

let data = await template.findOne({
  where:{
    id: crb.id
  }
});

新增数据

​ 传入需要新增的数据,使用create方法即可。

await history
  .create({
    dt: momentTime,
    username: crb.username,
    mail: crb.mail,
  })

删除数据

​ 根据传入的id,删除当前id下的所有数据

let data = await template.destroy({
  where:{
    id: crb.id
  }
});

修改数据

​ 根据id修改数据,需要同时传入数据及数据特征(寻找需要修改的数据)。

let data = await template.update({
  name: crb.name,
  keyword: crb.keyword,
  owner: crb.owner,
  update_time: momentTime,
  update_commit: crb.update_commit
},{
  where:{
    id: crb.id
  }
});

总结

以上就是简易的Sequelize与mysql的教程,如果需要更为复杂的可以去Sequelize官网查看详细教程。

猜你喜欢

转载自blog.csdn.net/qmzmzxk/article/details/82109582