Home  >  Article  >  Database  >  What is the method of node+mysql database connection pool connection?

What is the method of node+mysql database connection pool connection?

WBOY
WBOYforward
2023-05-30 21:35:241794browse

Mysql has two connection methods: one is direct connection and the other is pooled connection. We are talking about pooled connection in this article.

In order to clear up the confusion, I will briefly write the code for direct connection, as follows:

var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'ac',
  password : '123456',
  database : 'textPro'
});
 
connection.connect();
 
connection.query('SELECT * from1 userInfo', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results);
});
 
connection.end();

The difference between createConnection and createPool is: createPool (connection pool) connection can be more reasonable Utilize server data to reduce data waste

After installation, start writing in db/index.js:

const mysql = require("mysql")
 
//创建连接池
const db= mysql.createPool({  
    host : 'localhost', //连接主机
    port : 3306,   //端口号
    database : 'test',  //连接的是哪一个库
    user : 'root',   //用户名
    password : '',    //密码
    connectionLimit : 50, //用于指定连接池中最大的链接数,默认属性值为10. 
    //用于指定允许挂起的最大连接数,如果挂起的连接数超过该数值,就会立即抛出一个错误,
    //默认属性值为0.代表不允许被挂起的最大连接数。
    queueLimit:3 
})

After establishing the connection pool, you can directly use the connection pool objectgetConnection methodGet a connection from the connection pool. If there is no available connection in the connection pool, a database connection will be established implicitly.

const mysql = require("mysql")
 
//创建连接池
const db= mysql.createPool({  
    host : 'localhost', //连接主机
    port : 3306,   //端口号
    database : 'test',  //连接的是哪一个库
    user : 'root',   //用户名
    password : '',    //密码
    connectionLimit : 50, //用于指定连接池中最大的链接数,默认属性值为10. 
    //用于指定允许挂起的最大连接数,如果挂起的连接数超过该数值,就会立即抛出一个错误,
    //默认属性值为0.代表不允许被挂起的最大连接数。
    queueLimit:3 
})  
 
module.exports.query = (sql, values.callback) => {
  //err: 该参数是指操作失败时的错误对象。
  //connection: 该值为一个对象,代表获取到的连接对象。当连接失败时,该值为undefined。
  db.getConnection(function(err, connection) {
    if (err) {
      console.log('与mysql数据库建立连接失败');
      pool.releaseConnection(); //释放链接
    } else {
      console.log('与mysql数据库建立连接成功');
      connection.query(sql,values,(err, res) => {
        if (err) {
          console.log('执行sql语句失败,查询数据失败');
          //connection.release() 当一个连接不需要使用时,使用该方法将其归还到连接池中 release释放
          connection.release();
          callback(err,null)
        } else {
           console.log('执行sql语句成功');
           callback(null,res)
          //pool.end() 当一个连接池不需要使用时,可以使用该方法关闭连接池
          pool.end();
        }
      })
    }
  })
}

Introducing the calling db module

const query=require('./db').query;
let sql='SELECT * FROM class WHERE class_id=? AND class_name=?' 
let userId=1;
let userName='阿辰';
query(sql,[userId,userName],(err,res)=>{
    if(err){
        console.log('发生了错误***',err)
        return
    }
console.log('找到了',res)
})

The difference between const query=require('./db').query and const query=require('./db')

  • The first way of writing only obtains the query function in the "./db" module. If you need to use other export items, you need to obtain it again.

  • The second writing method obtains all the items exported by the "./db" module, and there is no need to repeatedly obtain different exported items in the code.

The above is the detailed content of What is the method of node+mysql database connection pool connection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete