看實(shí)例程式碼是這樣子的;
const mysql = require('mysql');
exports.base = (sql, data, callback) => {
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務(wù)器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
connection.query(sql, data, (err, rows) => {
if (err) throw err;
callback(rows);
});
// 關(guān)閉數(shù)據(jù)庫
connection.end();
}
感覺應(yīng)該是下面這樣的啊
const mysql = require('mysql');
exports.base = (sql, data, callback) => {
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務(wù)器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
connection.query(sql, data, (err, rows) => {
if (err) throw err;
callback(rows);
// 關(guān)閉數(shù)據(jù)庫
connection.end();
});
}
就是感覺資料庫關(guān)閉連線應(yīng)該是在查詢的回呼裡面完成啊,如果像第一種寫法,查詢還沒結(jié)束,就關(guān)閉資料庫,是不是不妥呢,這個mysql模組內(nèi)部原理不是很清楚;
望大家解惑啊;
認(rèn)證0級講師
文檔:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
所以,呼叫了end()
不會馬上關(guān)閉連接,要等剩余的查詢執(zhí)行完才關(guān)閉,該觸發(fā)的回調(diào)還是觸發(fā)。destroy()
才是直接關(guān)閉連線。
具體實(shí)作就是把全部操作都放到佇列裡執(zhí)行,end()
只是把一個Quit操作放入佇列,Quit操作執(zhí)行完後才真正關(guān)閉。