【发布时间】:2019-11-28 23:11:06
【问题描述】:
我正在尝试按照this 教程实现nodejs mysql 数据库。我知道
pool.query() 是 pool.getConnection() + connection.query() + connection.release().
文章中数据库配置为:
var mysql = require('mysql')
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'matt',
password: 'password',
database: 'my_database'
})
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
module.exports = pool
这可以用作:
pool.query('SELECT * FROM users', function (err, result, fields) {
if (err) throw new Error(err)
// Do something with result.
})
但是,我真的不明白这一点
if (connection) connection.release()
如果使用池自动释放连接,为什么我们需要这个?
【问题讨论】: