Reputation: 173
as we knows node has some mysql modules, some are pure js implemented(like node-mysql), some are based on c libmysql.
i quite prefer node-mysql because it doesn't need extra mysql library which seems more 'clean'. But i also notice that it does not support timeout feature in connect & query which may cause problem at some envrioment.
so my question is : does anyone have solve this timeout problem cleanly?
Upvotes: 4
Views: 6888
Reputation: 625
I have had the same issue, using the method mysql.createPool instead of the method createConnection have work for me.
This is my code;
/*jslint node: true */
'use strict';
var Q = require('q');
var mysql = require('mysql');
var _config;
var env = process.env.NODE_ENV || 'development';
if (env === 'development') {
_config = {
host : 'localhost',
user : 'root',
charset : 'latin1',
password : '123456',
database : 'DEVDB',
connectionLimit: 10
};
}else {
_config = {
host : 'PRODUCTIONHOST',
user : 'root',
charset : 'latin1',
password : 'PRODUCTIONPASS',
database: 'PRODUCTIONDB',
connectionLimit: 10
};
}
var _pool = mysql.createPool(_config);
var runquery = function() {
var deferred = Q.defer();
var args = Array.prototype.slice.call(arguments);
//console.log(args);
args.push(function(err, results){
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(results);
}
});
_pool.query.apply(_pool, args);
return deferred.promise;
};
module.exports = runquery;
Usage example;
runquery('select id from users where mail = ?', 'eugenioclrc')
.then(function(rows){
console.log(rows);
});
Upvotes: 0
Reputation: 3601
What we did to fix this was to check the error message, and re-connect if necessary
This is how they suggest it at https://github.com/felixge/node-mysql#server-disconnects
Here is the sample code in case the documentation ever changes
function handleDisconnect(connection) {
connection.on('error', function(err) {
if (!err.fatal) {
return;
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
throw err;
}
console.log('Re-connecting lost connection: ' + err.stack);
connection = mysql.createConnection(connection.config);
handleDisconnect(connection);
connection.connect();
});
}
handleDisconnect(connection);
Upvotes: 1