This time I will show you how node.js can connect to mysql through the connection pool. The following is a practical case, let’s take a look.
First let’s take a look at what a database connection pool is (from Baidu Encyclopedia): The database connection pool is responsible for allocating, managing and releasing database connections. It allows applications to reuse an existing database connection. Instead of re-establishing another one; release the database connection whose idle time exceeds the maximum idle time to avoid missing database connections caused by not releasing the database connection. This technology can significantly improve the performance of database operations.
Next, let’s see how node.js implements the database connection pool. Here, use mysql as an example;
The first step, npm install mysql module
$ npm install mysql -S
The first step, npm install mysql module
var mysql = require('mysql');// 创建 mysql 连接池资源var pool = mysql.createPool({ host : 'localhost', user : 'root', password : 'root', database : 'test'}); exports.query = function(sql, arr, callback){ //建立链接 pool.getConnection(function(err,connection){ if(err){throw err;return;} connection.query(sql,arr,function(error,results,fields){ //将链接返回到连接池中,准备由其他人重复使用 connection.release(); if(error) throw error; //执行回调函数,将数据返回 callback && callback(results,fields); }); }); };
Finally, we can call this module in other places to perform efficient database queries:
var db = require('./../model/db'); //require的路径是我们的db模块相对于本文件的路径db.query('select * from user', [], function(results,fields){ //查询后的回调 //Results代表是查询的结果,如果是插入修改等操作,则返回影响数据库信息的对象 // fields代表查询的字段信息}
Related recommendations:
nodejs uses connection pool to connect to mysql
nodeJs uses connection pool to connect to mysq
Node.js uses MySQL’s connection pool
The above is the detailed content of How node.js implements connection to mysql through connection pool. For more information, please follow other related articles on the PHP Chinese website!