others - Javascript - Node mysqljs 如何正确关闭连接

我正在使用mysqljs通过javascript访问MySQL 。

我像这样创建连接:


var connection = mysql.createConnection({


 //debug: ['ComQueryPacket'],


 host : dataSource.host,


 user : dataSource.user,


 password: dataSource.password,


 database: dataSource.database


});



我有三个函数可以进行数据库查询。

包含select查询的函数构建如下:


dbSearch(data){


 var sql ="SELECT * from table where field =? and otherfield=?";


 return new Promise((resolve, reject) => {


 connection.query(sql, [data[0], data[1], (error, results, fields) => {


 if (error){


 console.log(error);


 reject("Database connection error:" + error);


 } else {


 resolve(results);


 } 


 });


 });


}



代码在另一个函数中执行:


if (dataItem){


 dbSearch(dataItem)


 .then((row) => {


 processingfunction(row);


 });



如果我遗漏了connection.end(),代码将挂起,并且数据流在正在处理的第一项上被阻止。

如果我将connection.end()放入函数中,则会出现此错误:

Database connection error : Error : cannot enqueue Query after invoking quit .

我把connection.end()放到代码的最后一行,一切正常,

但是问题在于update和insert函数:


updateRecord(data){


 var sql ="UPDATE table set field=? where id=?";


 return new Promise((resolve, reject) => {


 connection.query(sql, [data[0], data[1], (error, results, fields) => {


 if (error){


 console.log(error);


 reject("Database connection error:" + error);


 } else {


 resolve(results);


 }


 });


 });


}



inputRecord(data){


 var sql ="INSERT INTO table (field1, field2, field3) VALUES(?,?,?)";


 return new Promise((resolve, reject) => {


 connection.query(sql, [data[0], data[1], data[2]], (error, results, fields) => {


 if (error){


 console.log(error);


 reject("Database connection error:" + error);


 } else {


 resolve(results);


 } 


 });


 });


}



在函数中使用connection end时出现此错误。


Database connection error: Error: Cannot enqueue Query after invoking quit.


(node:40700) UnhandledPromiseRejectionWarning: Database connection error: Error: Cannot enqueue Query after invoking quit.


(node:40700) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)


(node:40700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.



时间:

使用连接池时,不必手动关闭conn ,有一个.query()的便捷方法,


var mysql = require('mysql');


var pool = mysql.createPool({


 connectionLimit : 10,


 host : 'example.org',


 user : 'bob',


 password : 'secret',


 database : 'my_db'


});



pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {


 if (error) throw error;


 console.log('The solution is: ', results[0].solution);


});



...