我是node.js的新手。我只是想知道在node.js中可以重新连接数据库(mysql)吗?
我编写了以下代码,以便在数据库停机几秒钟时建立连接:
var http = require("http");
var mysql = require('mysql');
var trn_nbr="";
var amount1="";
var db_config = {
host : 'localhost',
user : 'root',
password : '',
database: 'realmoney'
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config);
connection.connect(function(err)
{
if(err)
{
console.log('error when connecting to db:', err);
//setTimeout(handleDisconnect, 10000);
handleDisconnect();
}
else
{
console.log("Now Connected");
connection = mysql.createConnection(db_config);
for (var i=0; i<1000; i++)
{
connection.query("select tran_nbr,tran_amount from tranlog", function(err, rows)
{
if(err)
{
if (err.code !== "PROTOCOL_CONNECTION_LOST")
throw err;
else
{
console.log('query error when connecting to db:', err);
//setTimeout(handleDisconnect, 10000);
handleDisconnect();
}
}
else
{
tran_nbr = rows[0].tran_nbr;
amount1 = rows[0].tran_amount;
console.log("tran_nbr:",tran_nbr);
console.log("Amount:",amount1);
//sleep.sleep(5);//sleep for 5 seconds
}
})
}
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST')
{
handleDisconnect();
}
else
{
throw err;
}
});
}
handleDisconnect();
你也可以告诉代码有什么问题来帮助我。
我使用以下代码来实现连接池,但是这段代码不起作用:
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database: 'realmoney'
});
exports.getUsers = function(callback) {
pool.getConnection(function(err, connection) {
if(err) { console.log(err); callback(true); return; }
var sql = "SELECT id,name FROM users";
connection.query(sql, [], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) { console.log(err); callback(true); return; }
callback(false, results);
});
});
});
我已经在我的服务器上安装了连接池模块。我在Linux服务器上运行node.js代码。 如果没有在node.js中重新启动应用程序,我可以重新连接mysql数据库吗?