数据库连接池以及sequelize实现增删改查等操作指南

吾爱主题 阅读:99 2024-04-01 23:20:56 评论:0
目录
  • 数据库连接池
    • 介绍数据库连接池
      • 优点
      • 使用方法
  • 数据库访问中的ORM——sequelize模块
    • ORM
    • sequelize模块——ORM的实现模块
  • 总结

数据库连接池

介绍数据库连接池

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。

通俗的理解就是: 数据库连接池是程序启动时建立足够数量的数据库连接对象,并将这些连接对象组成一个池,由程序动态的对池中的连接对象进行申请、使用和释放。

优点

(1)避免应用程序频繁的连接、断开数据库

(2)提供数据库连接对象的使用频率。

使用方法

(1)创建数据库连接池:

mysql.createPool(config) 
    host:数据库服务器的地址
    port: 端口号
    user:连接数据库的用户名
    password:连接数据库的密码
    database:数据库名
    connectionLimit:用于指定连接池中最大的链接数,默认属性值为10.
    multipleStatements :是否允许执行多条sql语句,默认值为false

(2)从连接池中获取一个连接

?
1 2 3 4 5 6 连接池名.getConnection( function (err,connection){      执行的代码 })   //参数err:错误对象。连接失败后的错误信息 //参数connection:连接对象。若连接失败,它就是undefined

(3)释放连接对象(将连接对象放回连接池): connection.release();

(4)从连接池中移除连接对象: connection.destory();

(5)关闭该连接池:  连接池名.end();

数据库访问中的ORM——sequelize模块

ORM

对象关系映射,主要解决面向对象编程与关系型数据库之间不匹配的问题。

ORM的特点

  • 可以提高开发的效率
  • 不用直接写SQL语句

sequelize模块——ORM的实现模块

基于promise的关系型数据库ORM框架,这个库完全采用JavaScript开发并且能够用在Node.JS环境中,易于使用,支持多SQL方言(dialect)。它当前支持MySQL、MariaDB、SQLite、PostgreSQL、Sql Server 数据库。

sequelize的特色

  • 强大的模型定义,支持虚拟类型。
  • 支持完善的数据验证,减轻前后端的验证压力。
  • Sequelize的查询非常全面和灵活。

sequelize的使用

数据库内容:数据库名称为spj,数据库表为 users表;

1、安装sequelize:npm install sequelize    --->必须先安装mysql的驱动模块(npm  install  mysql);

2、连接数据库:创建sequelize的对象;

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //导入mysql模块 const mysql = require( 'mysql2' ); //导入sequelize模块 const Sequelize = require( 'sequelize' ); //创建sequelize对象,参数分别为:数据库名称,数据库类型,密码,配置 var MySequelize = new Sequelize( 'spj' , 'root' , '929TJ813' ,{      host: 'localhost' ,      port:3306,      dialect: 'mysql' ,   //数据库类型      pool:{  //数据库连接池          max:20,  //最大连接对象的个数          min:5,  //最小连接对象的个数          idle:1000  //最长等待时间,单位为毫秒      } }) module.exports = MySequelize ;   //导出创建的sequelize对象

3、创建数据模型:数据模型是一个类,对应的是数据库中一张表;

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 const Sequelize =require( 'sequelize' ) const MySequesize = require( '../config/dbconfig' );  //导入创建的sequelize对象 //创建StudentModel模型,该模型对应的表名是student var StudentModel = MySequesize.define( 'users' ,{      sid:{          type:Sequelize.INTEGER,  //表示属性的数据类型          field: 's_id' ,   //属性对应的列名,若不定义field则表中的列名(sid)就是属性名          primaryKey: true //表示主键          autoIncrement: true  //表示主键自增      },      sname:{          type:Sequelize.STRING(50),          field: 's_name' ,          allowNull: false ,   //表示当前列是否允许为空,false表示该列不能为空          //unique:true    //表示该列的值必须唯一      },      sgender:{          type:Sequelize.STRING(4),          field: 's_gender' ,          allowNull: false      },      sbirthday:{          type:Sequelize.DATE,          field: 's_birthday' ,          allowNull: false      },      saddress:{          type:Sequelize.STRING(100),          field: 's_address' ,          allowNull: false      },      sage:{          type:Sequelize.INTEGER,          field: 's_age' ,          allowNull: false      } },{      freezeTableName: true , //true表示使用给定的表名,false表示模型名后加s作为表名      timestamps: false  //true表示给模型加上时间戳属性(createAt、updateAt),false表示不带时间戳属性 }) //同步数据库,force的值为false,表若存在则先删除后创建,force的值为true表示表若存在则不创建 var users = StudentModel.sync({force: false });   module.exports = StudentModel;   //导出模型

4、使用sequelize实现增删改查 。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 const StudentModel = require( '../../db/model/StudentModel' ); const Sequelize = require( 'sequelize' ) //插入数据 StudentModel.create({      sname: '关羽' ,      sgender: '男' ,      sbirthday: '1998-12-28' ,      saddress: '陕西宝鸡' }).then(result=>{      console.log( "插入成功!" ,result); }). catch (err=>{      console.log( "插入失败!" ,err); })   //查询数据 StudentModel.findAll({      raw: true   //查询出来只有需要的数据,没有别的内容 }).then(data=>{      console.log(data); })   //删除记录 StudentModel.destroy({      where:{          sid:2      } }).then(result=>{      console.log( "删除成功!" ,result) }). catch (err=>{      console.log( "删除失败!" ,err); })   //更新记录 StudentModel.findOne({      where:{          sid:3      } }).then(users=>{      users.update({          sname: '张飞' ,          sgender: '男'      }).then(result=>{          console.log( "更新成功!" ,result)      }). catch (err=>{          console.log( "更新失败!" ,err);      }) }). catch (error=>{      console.log( "查无此人!" ,error); })   //查询部分字段 StudentModel.findAll({      attributes:[ 'sname' , 'saddress' ],      raw: true }).then(result=>{      console.log(result); }). catch (err=>{      console.log(err); })   //聚合函数 StudentModel.findAll({      attributes:[[Sequelize.fn( 'COUNT' ,Sequelize.col( 's_id' )), "记录总数" ]],  //col里面必须放的是列名      raw: true }).then(result=>{      console.log(result) })

5、使用sequelize实现模糊查询等内容。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 const StudentModel = require( '../../db/model/StudentModel' ); const Op = require( 'sequelize' ).Op;   //引入sequelize模块的Op操作符   //模糊查询 StudentModel.findAll({      where:{          sname:{              [Op.like]: '张%'          }      },      raw: true }).then(result=>{      console.log(result); })   //between:查询年龄在12到18之间的人的信息 StudentModel.findAll({      where:{          sage:{              [Op.between]:[12,18]          }      },      raw: true }).then(result=>{      console.log(result); })   //in:查询地址是'陕西西安‘和'陕西商洛‘的记录 StudentModel.findAll({      where:{          saddress:{              [Op. in ]:[ '陕西西安' , '陕西商洛' ]          }      },      order:[        [ 'sage' , 'desc' ]   //查询结果按照sage的降序排列      ],      raw: true }).then(result=>{      console.log(result); })   //and和or:查询性别为'男‘,并且地址是‘陕西宝鸡'的记录 StudentModel.findAll({      where:{          [Op.and]:[   //把and改为or即为或时间              {                  sgender:{                      [Op.eq]: '男'                  }              },              {                  saddress:{                      [Op.eq]: '陕西宝鸡'                  }              }          ]      },      raw: true }).then(result=>{      console.log(result); })   //limit和offset:分页查询 StudentModel.findAll({      limit:3,   //查询的记录数      offset:1,  //从索引值为几的记录开始查询(查询的起始位置),所有数据的索引值从0开始      raw: true }).then(result=>{      console.log(result); })

总结

到此这篇关于数据库连接池以及sequelize实现增删改查等操作指南的文章就介绍到这了,更多相关数据库连接池及sequelize增删改查内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/TangJing_/article/details/121602581

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容