Node.js 連接mysql數(shù)據(jù)庫問題
問題描述
問題描述: 最近在玩node.js連接mysql數(shù)據(jù)庫,也連接成功,可以增刪改了。但是有一個問題,每當(dāng)拋出異常時,我的程序自動停止???并且報以下錯誤:
events.js:160 throw er; // Unhandled ’error’ event ^Error: Connection lost: The server closed the connection. at Protocol.end (D:SoftWareZBJWORKSPACEWebStormWKnode-log-regnode_modulesmysqllibprotocolProtocol.js:109:13) at Socket.<anonymous> (D:SoftWareZBJWORKSPACEWebStormWKnode-log-regnode_modulesmysqllibConnection.js:109:28) at emitNone (events.js:91:20) at Socket.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9)
很奇怪為什么自動停止程序?我的連接數(shù)據(jù)庫程序如下:
var mysql = require(’mysql’);var db_config = { host: ’127.0.0.1’, port:’3306’, user: ’root’, password: ’root’, database: ’test’};function connectServer() { var client = mysql.createConnection(db_config); return client;}function selectFun(client, username, callback) { //console.log('查詢參數(shù):'+username); //client為一個mysql連接對象 client.query(’select * from user where name='’ + username + ’'’, function (err, results, fields) { // console.log('查詢結(jié)果:'+results);if (err) throw err;callback(results); });}function insertFun(client, username, password, callback) { var usr = {name:username,pwd:password}; client.query(’insert into user set ?’, usr, function (err, result) {if (err) { console.log('error:' + err.message); return err;}callback(result); });}exports.connect = connectServer;exports.selectFun = selectFun;exports.insertFun = insertFun;
問題解答
回答1:不要在回調(diào)函數(shù)中拋出異常,需要使用nodejs的方式:
callback(e,result,...);回調(diào)函數(shù)的第一個參數(shù)為Error對象,如果沒發(fā)生錯誤,傳入null
相關(guān)文章:
1. 安全性測試 - nodejs中如何防m(xù)ySQL注入2. javascript - 關(guān)于apply()與call()的問題3. html - eclipse 標(biāo)簽錯誤4. python 利用subprocess庫調(diào)用mplayer時發(fā)生錯誤5. python - Pycharm的Debug用不了6. datetime - Python如何獲取當(dāng)前時間7. 請問PHPstudy中的數(shù)據(jù)庫如何創(chuàng)建索引8. python - pycharm 自動刪除行尾空格9. python文檔怎么查看?10. javascript - nginx反向代理靜態(tài)資源403錯誤?
