In the pursuit of optimizing MySQL usage within a Node.js application, connection pooling emerges as a crucial strategy. Utilizing the node-mysql module, a custom module named mysql.js can be crafted to establish a connection pool:
<code class="js">var mysql = require('mysql'); var pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'root', database: 'guess' }); exports.pool = pool;</code>
By implementing this module, subsequent MySQL queries can be executed by accessing the pool:
<code class="js">var mysql = require('../db/mysql').pool; var test = function(req, res) { mysql.getConnection(function(err, conn){ conn.query("select * from users", function(err, rows) { res.json(rows); }) }) }</code>
This approach offers several advantages, including:
To ensure proper resource management, it's essential to release connections after completing queries:
<code class="js">connection.release();</code>
Alternatively, rewrite the exports section of the mysql module to directly return a connection, eliminating the need for getConnection():
<code class="js">var getConnection = function(callback) { pool.getConnection(function(err, connection) { callback(err, connection); }); }; module.exports = getConnection;</code>
This revised approach streamlines the connection-acquisition process while maintaining the benefits of connection pooling.
The above is the detailed content of How Can Connection Pooling Enhance MySQL Connectivity in Node.js Applications?. For more information, please follow other related articles on the PHP Chinese website!