当前位置:网站首页>[node] node uses MySQL connection pool

[node] node uses MySQL connection pool

2022-06-22 00:16:00 Silent tubule

Step on pit No easy , also Greek at various position Big Guy the a One Next \textcolor{gray}{ It's not easy to step on the pit , I also hope you guys can support } Step on pit No easy , also Greek at various position Big Guy the a One Next

individual people Lord page : \textcolor{green}{ Personal home page :} individual people Lord page Silent tubule

individual people network standing : \textcolor{green}{ Personal website :} individual people network standing Silent tubule

Technology Technique hand over flow Q Q Group : : 837051545 \textcolor{green}{ Technical communication QQ Group ::837051545} Technology Technique hand over flow QQ Group :837051545

spot Fabulous , you Of recognize can yes I gen do Of dynamic force ! \textcolor{green}{ give the thumbs-up , Your recognition is the driving force of my creation !} spot Fabulous , you Of recognize can yes I gen do Of dynamic force

closed hidden , you Of green look at yes I No force Of Fang towards ! \textcolor{green}{ Collection , Your favor is the direction of my efforts !} closed hidden , you Of green look at yes I No force Of Fang towards

review On , you Of It means see yes I Into the Step Of goods rich ! \textcolor{green}{ Comment on , Your opinion is the wealth of my progress !} review On , you Of It means see yes I Into the Step Of goods rich

If you don't understand, you can leave a message , I should see a reply
If there is a mistake , Your advice are most welcome

1. What is? mysql Connection pool

The database connection pool is a database connection object with sufficient number when the program starts , A pool composed of , from node The program dynamically calls the objects in the pool , Connect , Use , Release , Shut down etc

2. Why use mysql Connection pool

Why use mysql Connection pool , Instead of a single connection mysql, Use on link , Close after use , Isn't that convenient ?
Okay ~~~~ At the beginning, I also referred to the online code for convenience , Use a single link mysql Of , But there's a problem : After I connected, I closed , During this period , I have another program to execute mysql, But during this period, another program thought it was a link mysql The success of , Just as he was about to execute , The last program has put mysql Disconnect the , This results in an error ( Need to reconnect mysql), The interface on the client side is red ~~~

3.node Use mysql Connection pool

install mysql

npm -install -g node-mysql

Use mysql Connection pool

//*- coding = utf-8 -*-
//@Time : 2022-01-17 1:25
//@Author :  silence 
//@File : userService.js
//@web : www.php-china.com
//@Software: WebStorm
//  The database class 
const mysql = require("mysql"),// Need to install mysql expand 
  config = require("../utils/config")// The configuration file 

class Model {
    
  // Connection object static properties -- Static attributes are generated and destroyed simultaneously with class creation 
  static conn = null;
  constructor() {
    
  }
  // Static method of linking database 
  static connection() {
    
    let host = config.baseConfig.host;
    let user = config.baseConfig.user;
    let password = config.baseConfig.password;
    let database = config.baseConfig.database;

    //mysql Connection pool 
    Model.conn = mysql.createPool({
    
      host,//" Database server address ",
      port: "3306", // MySQL Database port number 
      database,// " Database name ",
      user,//" User name to connect to the database ",
      password,//" Password to connect to the database ",
      connectionLimit: 20,//" Specify the maximum number of links in the connection pool , The default is 10",
      multipleStatements: true,//" Whether to run and execute multiple sql sentence , The default value is false"
    })
    console.log(` Database connection successful `);
  }
  /** *  Operation of database -- Open transaction  * @param sql  Operation statement executed  * @param params  to sql An array of parameters assigned to the placeholder of the statement  * @returns {Promise<unknown>} */
  static query(sql, params = []) {
    
    return new Promise((resolve, reject) => {
    
      this.connection();
      Model.conn.getConnection((err,conn) => {
    
        if (err) {
    
          console.log(` Database connection failed :${
      err.message}`);
        }else{
    
          conn.query(sql, params, (err, res) => {
    
            if (err) {
    
              console.log(' Database query failed ', err)
              reject(err)
            } else {
    
              resolve(res)
            }
          })
          conn.release();// Release the connection 
        }
      })
    })
  }
}
module.exports = Model;

call mysql Connection pool

const model = require('../../index');
const utilsTool = require('../../../utils/utils');
class Index extends model{
    
 /** *  Get a list of all appointments for the next day  */
  static test(curEndTime,timeType){
    
    return new Promise((resolve,reject)=>{
    
      let sql = `SELECT * FROM xxx WHERE xxx > ? AND timeType=?`;
      this.query(sql,[curEndTime,timeType]).then(res=>{
    
        resolve(res);
      }).catch(err=>{
    
        console.log(` error message :${
      err.message}`);
        reject(err);
      })
    })
  }
}
原网站

版权声明
本文为[Silent tubule]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206212226029509.html