Look at the example code like this;
const mysql = require('mysql');
exports.base = (sql, data, callback) => {
// 創(chuàng)建數(shù)據(jù)庫(kù)連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫(kù)所在的服務(wù)器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫(kù)名稱
});
// 執(zhí)行連接動(dòng)作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫(kù)操作
connection.query(sql, data, (err, rows) => {
if (err) throw err;
callback(rows);
});
// 關(guān)閉數(shù)據(jù)庫(kù)
connection.end();
}
It should look like this
const mysql = require('mysql');
exports.base = (sql, data, callback) => {
// 創(chuàng)建數(shù)據(jù)庫(kù)連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫(kù)所在的服務(wù)器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫(kù)名稱
});
// 執(zhí)行連接動(dòng)作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫(kù)操作
connection.query(sql, data, (err, rows) => {
if (err) throw err;
callback(rows);
// 關(guān)閉數(shù)據(jù)庫(kù)
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;
認(rèn)證0級(jí)講師
Documentation:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
So, calling end()
不會(huì)馬上關(guān)閉連接,要等剩余的查詢執(zhí)行完才關(guān)閉,該觸發(fā)的回調(diào)還是觸發(fā)。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.