我继承了一些node.js代码,我不知道它是如何工作的。我遇到的问题是打开数据库连接,而不是关闭或重复使用它们。所以在某些时候,我不得不杀死节点进程来释放连接,否则数据库就会开始抱怨。我试图自己关闭连接,但不能理解基于事件的逻辑,因为在第二个查询可以运行或者根本不运行之前,我最终会关闭连接。我在Ubuntu 12.04.2 LTS上使用节点0.6.12,节点mysql模块为v0.9.6。以下是一个示例模型方法。Node.js关闭数据库连接
this.search = function(options, callback) {
if (options.post) {
var query;
var param;
var limit;
var results_per_page = 10;
var page = (options.post.hasOwnProperty('page') && parseInt(options.post.page)) ? options.post.page : 1;
limit = ' LIMIT ' + ((page-1)*(results_per_page)) + ',' + results_per_page;
if (options.post.term) {
var escaped_term = options.database_client.escape('%' + options.post.term + '%');
query = "Q" + limit;
} else {
query = "Q" + limit;
}
options.database_client.query(query, [], query_results);
// Tried closing DB connection here
function query_results(err, results, fields) {
var all_results = {};
all_results.total_results = 0;
all_results.total_pages = 0;
all_results.current_page = page;
all_results.results = [];
if (err) {
console.log('You have an error: ' + err);
throw err;
} else {
if(!results[0]) {
callback(undefined, all_results);
return;
} else{
options.database_client.query("SELECT found_rows() AS total", [], function(err, results2, fields) {
if (err) {
console.log('You have an error: ' + err);
throw err;
} else {
if (!results2[0]) {
callback(undefined, all_results);
return;
} else {
var all_results = {};
all_results.total_results = results2[0].total;
all_results.total_pages = Math.ceil(all_results.total_results/results_per_page);
all_results.current_page = page;
for(var property in results) {
if(results.hasOwnProperty(property)){
if(results[property] == "" || results[property] == " "){
results[property] = null;
}
}
}
all_results.results = results;
}
callback(undefined, all_results);
return;
}
}); // end query
}
}
// I think here is only closing one connection
options.database_client.end();
}
// Also tried here but total_pages, total_results end up being 0 in the results callback
}
};
我使用options.database_client.end();
收每Node.js的mysql的模块,文档数据库连接。任何帮助将不胜感激。