Look at the example code like this;
const mysql = require('mysql');
exports.base = (sql, data, callback) => {
// 创建数据库连接
let connection = mysql.createConnection({
host: 'localhost', //数据库所在的服务器域名或者IP
user: 'root', //用户名
password: '', //密码
database: 'book' //数据库名称
});
// 执行连接动作
connection.connect();
// 执行数据库操作
connection.query(sql, data, (err, rows) => {
if (err) throw err;
callback(rows);
});
// 关闭数据库
connection.end();
}
It should look like this
const mysql = require('mysql');
exports.base = (sql, data, callback) => {
// 创建数据库连接
let connection = mysql.createConnection({
host: 'localhost', //数据库所在的服务器域名或者IP
user: 'root', //用户名
password: '', //密码
database: 'book' //数据库名称
});
// 执行连接动作
connection.connect();
// 执行数据库操作
connection.query(sql, data, (err, rows) => {
if (err) throw err;
callback(rows);
// 关闭数据库
connection.end();
});
}
I just feel that closing the database connection should be done in the callback of the query. If it is written like the first way and the query is not finished, is it inappropriate to close the database? The internal principle of this mysql module is not very clear;
Hope everyone can clear up the confusion;
Documentation:
So, calling
end()
不会马上关闭连接,要等剩余的查询执行完才关闭,该触发的回调还是触发。destroy()
will directly close the connection.The specific implementation is to put all operations into the queue for execution.
end()
Just put a Quit operation into the queue, and it is actually closed after the Quit operation is executed.