[前端] Nodejs中koa2连接mysql的实现示例

1872 0
Honkers 2022-10-21 15:25:00 | 显示全部楼层 |阅读模式
目录

    将查询结果转为对象或者数组mysql2的使用
      Prepared Statement(预处理语句)Connection Pools(连接池)Promise方式
    sequelize
      Sequelize的使用Sequelize的单表操作Sequelize的一对多操作Sequelize的多对多操作



将查询结果转为对象或者数组

在真实开发中,实际上某些查询结果应该放入到一个对象中
JSON_OBJECT:()中是key-value的形式
  1. SELECT products.id as id, products.title as title, products.price as price, products.score as score,
  2.         JSON_OBJECT('id', brand.id, 'name', brand.name, 'rank', brand.phoneRank, 'website', brand.website) as brand
  3. FROM products LEFT JOIN brand ON products.brand_id = brand.id;
复制代码


在多对多关系中,我们希望查询到的是一个数组:
    比如一个学生的多门课程信息,应该是放到一个数组中的;数组中存放的是课程信息的一个个对象;这个时候我们要JSON_ARRAYAGGJSON_OBJECT结合来使用;

  1. SELECT stu.id, stu.name, stu.age,
  2.         JSON_ARRAYAGG(JSON_OBJECT('id', cs.id, 'name', cs.name)) as courses
  3. FROM students stu
  4. LEFT JOIN students_select_courses ssc ON stu.id = ssc.student_id
  5. LEFT JOIN courses cs ON ssc.course_id = cs.id
  6. GROUP BY stu.id;
复制代码
mysql2的使用

安装mysql2:
  1. npm install mysql2
复制代码
简单使用:
  1. const mysql = require('mysql2');
  2. // 1.创建数据库连接
  3. const connection = mysql.createConnection({
  4.   host: 'localhost',
  5.   port: 3306,
  6.   database: 'coderhub',
  7.   user: 'root',
  8.   password: 'Coderwhy888.'
  9. });
  10. // 2.执行SQL语句
  11. const statement = `
  12.   SELECT * FROM products WHERE price > 6000;
  13. `
  14. connection.query(statement, (err, results, fields) => {
  15.   console.log(results);
  16. });
复制代码
如果我们想要在拿到数据后停止服务,可以在回调函数中写上:
  1. connection.end()
复制代码
完整代码:
  1. connection.query(statement, (err, results, fields) => {
  2.   console.log(results);
  3.   connection.end();
  4. });
复制代码
Prepared Statement(预处理语句)

提高性能:将创建的语句模块发送给MySQL,然后MySQL编译(解析、优化、转换)语句模块,并且存储
它但是不执行,之后我们在真正执行时会给?提供实际的参数才会执行;就算多次执行,也只会编译一次,所以性能是更高的;
强调:如果再次执行该语句,它将会从LRU(Least Recently Used) Cache中获取获取,省略了编译statement的时间来提高性能。
  1. // 2.执行SQL语句: 使用 ?来对参数进行占位
  2. const statement = `
  3.   SELECT * FROM products WHERE price > ? AND score > ?;
  4. `
  5. connection.execute(statement, [6000, 7], (err, results) => {
  6.   console.log(results);
  7. });
复制代码
Connection Pools(连接池)

前面我们是创建了一个连接(connection),但是如果我们有多个请求的话,该连接很有可能正在被占用,那么我们是否需要每次一个请求都去创建一个新的连接呢?
    事实上,mysql2给我们提供了连接池(connection pools);连接池可以在需要的时候自动创建连接,并且创建的连接不会被销毁,会放到连接池中,后续可以继续使用;我们可以在创建连接池的时候设置LIMIT,也就是最大创建个数;
判断是否连接成功
  1. const mysql = require('mysql2');
  2. // 1.创建连接池
  3. const connections = mysql.createPool({
  4.   host: 'localhost',
  5.   port: 3306,
  6.   database: 'coderhub',
  7.   user: 'root',
  8.   password: 'Coderwhy888.',
  9.   connectionLimit: 10
  10. });
  11. connections.getConnection((err, conn) => {
  12.   conn.connect((err) => {
  13.     if(err){
  14.       console.log('连接失败:',err)
  15.     } else {
  16.       console.log('数据库连接成功~')
  17.     }
  18.   })
  19. })
复制代码
简单使用数据库
  1. const mysql = require('mysql2');
  2. // 1.创建连接池
  3. const connections = mysql.createPool({
  4.   host: 'localhost',
  5.   port: 3306,
  6.   database: 'coderhub',
  7.   user: 'root',
  8.   password: 'Coderwhy888.',
  9.   connectionLimit: 10
  10. });
  11. // 2.使用连接池
  12. const statement = `
  13.   SELECT * FROM products WHERE price > ? AND score > ?;
  14. `
  15. connections.execute(statement, [6000, 7], (err, results) => {
  16.   console.log(results);
  17. });
复制代码
Promise方式
  1. const mysql = require('mysql2');
  2. // 1.创建连接池
  3. const connections = mysql.createPool({
  4.   host: 'localhost',
  5.   port: 3306,
  6.   database: 'coderhub',
  7.   user: 'root',
  8.   password: 'Coderwhy888.',
  9.   connectionLimit: 10
  10. });
  11. // 2.使用连接池
  12. const statement = `
  13.   SELECT * FROM products WHERE price > ? AND score > ?;
  14. `
  15. connections.promise().execute(statement, [6000, 7]).then(([results,fields]) => {
  16.   console.log(results);
  17. }).catch(err => {
  18.   console.log(err);
  19. });
复制代码
sequelize

对象关系映射(ORM):是一种程序设计的方案:
    从效果上来讲,它提供了一个可在编程语言中,使用虚拟对象数据库的效果
Node当中的ORM我们通常使用的是sequelize;
    Sequelize是用于Postgres,MySQL,MariaDB,SQLite和Microsoft SQL Server的基于Node.js 的ORM;它支持非常多的功能;
如果我们希望将Sequelize和MySQL一起使用,那么我们需要先安装两个东西:
    mysql2:sequelize在操作mysql时使用的是mysql2;sequelize:使用它来让对象映射到表中;
  1. npm install sequelize mysql2
复制代码
Sequelize的使用

Sequelize的连接数据库:
第一步:创建一个Sequelize的对象,并且指定数据库、用户名、密码、数据库类型、主机地址等;
第二步:测试连接是否成功;
  1. const { Sequelize } = require('sequelize');
  2. const sequelize = new Sequelize('coderhub', 'root', 'Coderwhy888.', {
  3.   host: 'localhost',
  4.   dialect: 'mysql'//连接的数据库类型:mysql,mongoose
  5. });
  6. sequelize.authenticate().then(() => {
  7.   console.log("连接数据库成功~");
  8. }).catch(err => {
  9.   console.log("连接数据库失败~", err);
  10. });
复制代码
Sequelize的单表操作
  1. const { Sequelize, DataTypes, Model, Op } = require('sequelize');
  2. const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', {
  3.   host: 'localhost',
  4.   dialect: 'mysql'
  5. })
  6. //1.首先我们需要将数据库中的一张表映射成一个class类
  7. class Product extends Model {}
  8. Product.init({
  9.   id: {
  10.     type: DataTypes.INTEGER,
  11.     primaryKey: true,//主键
  12.     autoIncrement: true//自动增长
  13.   },
  14.   title: {
  15.     type: DataTypes.STRING,
  16.     allowNotNull: false//是否可以为空
  17.   },
  18.   price: DataTypes.DOUBLE,
  19.   score: DataTypes.DOUBLE
  20. }, {//与数据库的表进行映射的配置
  21.   tableName: 'products',
  22.   createdAt: false,
  23.   updatedAt: false,
  24.   sequelize
  25. });
  26. //存放操作数据库的代码
  27. async function queryProducts() {
  28.   //1.查询数据库中product表中所有的内容
  29.   const result1 = await Product.findAll({
  30.     where: {//在这里配置条件
  31.       price: {
  32.         [Op.gte]: 5000//意思是价格大于等于5000
  33.         //gte:大于等于,gt:大于,lt:小于,lte:小于等于
  34.       }
  35.     }
  36.   });
  37.   console.log(result1);
  38.   // 2.插入数据
  39.   const result2 = await Product.create({
  40.     title: "三星Nova",
  41.     price: 8888,
  42.     score: 5.5
  43.   });
  44.   console.log(result2);
  45.   // 3.更新数据
  46.   const result3 = await Product.update({
  47.     price: 3688
  48.   }, {
  49.     where: {
  50.       id: 1
  51.     }
  52.   });
  53.   console.log(result3);
  54. }
  55. queryProducts();//执行这个函数可以实现对数据库的操作
复制代码
Sequelize的一对多操作
  1. const { Sequelize, DataTypes, Model, Op } = require('sequelize');
  2. const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', {
  3.   host: 'localhost',
  4.   dialect: 'mysql'
  5. });
  6. //数据库的第一个表: 主表
  7. class Brand extends Model {};
  8. Brand.init({
  9.   id: {
  10.     type: DataTypes.INTEGER,
  11.     primaryKey: true,
  12.     autoIncrement: true
  13.   },
  14.   name: {
  15.     type: DataTypes.STRING,
  16.     allowNotNull: false
  17.   },
  18.   website: DataTypes.STRING,
  19.   phoneRank: DataTypes.INTEGER
  20. }, {
  21.   tableName: 'brand',
  22.   createdAt: false,
  23.   updatedAt: false,
  24.   sequelize
  25. });
  26. //数据库的第二个表:附表
  27. class Product extends Model {}
  28. Product.init({
  29.   id: {
  30.     type: DataTypes.INTEGER,
  31.     primaryKey: true,
  32.     autoIncrement: true
  33.   },
  34.   title: {
  35.     type: DataTypes.STRING,
  36.     allowNotNull: false
  37.   },
  38.   price: DataTypes.DOUBLE,
  39.   score: DataTypes.DOUBLE,
  40.   brandId: {
  41.     field: 'brand_id',
  42.     type: DataTypes.INTEGER,
  43.     references: {//这张表使用了Brand的id作为外键
  44.       model: Brand,//product这张表使用了Brand这个表,所以product必须放在下面
  45.       key: 'id'
  46.     }
  47.   }
  48. }, {
  49.   tableName: 'products',
  50.   createdAt: false,
  51.   updatedAt: false,
  52.   sequelize
  53. });
  54. // 将两张表联系在一起
  55. Product.belongsTo(Brand, {
  56.   foreignKey: 'brandId'//外键
  57. });
  58. async function queryProducts() {
  59.   const result = await Product.findAll({
  60.     include: { //这里是联合查询:意思是包含别的表的信息
  61.       model: Brand
  62.     }
  63.   });
  64.   console.log(result);
  65. }
  66. queryProducts();
复制代码
Sequelize的多对多操作
  1. const { Sequelize, DataTypes, Model, Op } = require('sequelize');
  2. const sequelize = new Sequelize("coderhub", 'root', 'Coderwhy888.', {
  3.   host: 'localhost',
  4.   dialect: 'mysql'
  5. });
  6. // Student表
  7. class Student extends Model {}
  8. Student.init({
  9.   id: {
  10.     type: DataTypes.INTEGER,
  11.     primaryKey: true,
  12.     autoIncrement: true
  13.   },
  14.   name: {
  15.     type: DataTypes.STRING,
  16.     allowNotNull: false
  17.   },
  18.   age: DataTypes.INTEGER
  19. }, {
  20.   tableName: 'students',
  21.   createdAt: false,
  22.   updatedAt: false,
  23.   sequelize
  24. });
  25. // Course表
  26. class Course extends Model {}
  27. Course.init({
  28.   id: {
  29.     type: DataTypes.INTEGER,
  30.     primaryKey: true,
  31.     autoIncrement: true
  32.   },
  33.   name: {
  34.     type: DataTypes.STRING,
  35.     allowNotNull: false
  36.   },
  37.   price: DataTypes.DOUBLE
  38. }, {
  39.   tableName: 'courses',
  40.   createdAt: false,
  41.   updatedAt: false,
  42.   sequelize
  43. });
  44. // StudentCourse表:关系表
  45. class StudentCourse extends Model {}
  46. StudentCourse.init({
  47.   id: {
  48.     type: DataTypes.INTEGER,
  49.     primaryKey: true,
  50.     autoIncrement: true
  51.   },
  52.   studentId: {//与Student表建立关系
  53.     type: DataTypes.INTEGER,
  54.     references: {
  55.       model: Student,
  56.       key: 'id'
  57.     },
  58.     field: 'student_id'
  59.   },
  60.   courseId: {//与Course表建立关系
  61.     type: DataTypes.INTEGER,
  62.     references: {
  63.       model: Course,
  64.       key: 'id'
  65.     },
  66.     field: 'course_id'
  67.   }
  68. }, {
  69.   tableName: 'students_select_courses',
  70.   createdAt: false,
  71.   updatedAt: false,
  72.   sequelize
  73. });
  74. // 多对多关系的联系:Student StudentCourse Course
  75. Student.belongsToMany(Course, {
  76.   through: StudentCourse,
  77.   foreignKey: 'studentId',//这里是Student与StudentCourse,所以外键是studentId
  78.   otherKey: 'courseId'//StudentCourse与Course,所以外键是courseId
  79. });
  80. //与上面类似
  81. Course.belongsToMany(Student, {
  82.   through: StudentCourse,
  83.   foreignKey: 'courseId',
  84.   otherKey: 'studentId'
  85. });
  86. async function queryProducts() {
  87.   const result = await Student.findAll({
  88.     include: {//所有学生的选课情况
  89.       model: Course
  90.     }
  91.   });
  92.   console.log(result);
  93. }
  94. queryProducts();
复制代码
到此这篇关于Nodejs中koa2连接mysql的实现示例的文章就介绍到这了,更多相关koa2连接mysql内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

特级红客

关注
  • 3159
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行