javascript - 關(guān)于用mysql模塊連接數(shù)據(jù)庫的一點(diǎn)疑問
問題描述
看實(shí)例代碼是這樣子的;
const mysql = require(’mysql’);exports.base = (sql, data, callback) => { // 創(chuàng)建數(shù)據(jù)庫連接 let connection = mysql.createConnection({host: ’localhost’, //數(shù)據(jù)庫所在的服務(wù)器域名或者IPuser: ’root’, //用戶名password: ’’, //密碼database: ’book’ //數(shù)據(jù)庫名稱 }); // 執(zhí)行連接動(dòng)作 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ù)器域名或者IPuser: ’root’, //用戶名password: ’’, //密碼database: ’book’ //數(shù)據(jù)庫名稱 }); // 執(zhí)行連接動(dòng)作 connection.connect(); // 執(zhí)行數(shù)據(jù)庫操作 connection.query(sql, data, (err, rows) => {if (err) throw err;callback(rows);// 關(guān)閉數(shù)據(jù)庫connection.end(); }); }
就是感覺 數(shù)據(jù)庫關(guān)閉連接應(yīng)該是在查詢的回調(diào)里面完成啊,如果像第一種寫法,查詢還沒結(jié)束,就關(guān)閉數(shù)據(jù)庫,是不是不妥呢,這個(gè)mysql模塊內(nèi)部原理不是很清楚;望大家解惑啊;
問題解答
回答1:文檔:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
所以,調(diào)用了end()不會(huì)馬上關(guān)閉連接,要等剩余的查詢執(zhí)行完才關(guān)閉,該觸發(fā)的回調(diào)還是觸發(fā)。destroy()才是直接關(guān)閉連接。
具體實(shí)現(xiàn)就是把全部操作都放到隊(duì)列里執(zhí)行,end()只是把一個(gè)Quit操作放入隊(duì)列,Quit操作執(zhí)行完之后才真正關(guān)閉。
相關(guān)文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問4. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?5. 實(shí)現(xiàn)bing搜索工具urlAPI提交6. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問?7. css - 寫頁面遇到個(gè)布局問題,求大佬們幫解答,在線等,急!~8. phpstudy8.1支持win11系統(tǒng)嗎?9. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語法錯(cuò)誤10. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化

網(wǎng)公網(wǎng)安備