Mysql query throws ECONNREFUSED in a Node.js scheduler job - mysql

I'm trying to build a scheduler with node (v0.10.33) using the node-schedule and node-mysql modules. Code as follows:
var schedule = require('node-schedule');
var mysql = require('mysql');
var rule = new schedule.RecurrenceRule();
rule.second = 59;
schedule.scheduleJob(rule, function(){
var connection = db.connect();
console.log('Successfully established database connection.');
var resultSet = db.select(connection, 'SELECT * from notifications');
db.disconnect(connection);
});
var db = {
connect: function(){
var connection = mysql.createConnection({
host : 'localhost',
user : 'scheduler',
password : 'scheduler'
});
console.log('Trying to establish connection with database...');
connection.connect();
return connection;
},
select: function(connection, queryString){
console.log('Executing database query...');
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].messagetext);
return rows;
});
},
disconnect: function(connection){
connection.end();
}
}
When I execute the scheduler I get the following output:
Trying to establish connection with database...
Successfully established database connection.
Executing database query...
/home/user/notificationscheduler/scheduler.js:32
if (err) throw err;
^
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
--------------------
at Protocol._enqueue (/home/user/notificationscheduler/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/home/user/notificationscheduler/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/home/user/notificationscheduler/node_modules/mysql/lib/Connection.js:119:18)
at Object.db.connect (/home/user/notificationscheduler/scheduler.js:25:14)
at Job.db.connect.mysql.createConnection.host [as job] (/home/user/notificationscheduler/scheduler.js:9:25)
at Job.invoke (/home/user/notificationscheduler/node_modules/node-schedule/lib/schedule.js:117:10)
at null._onTimeout (/home/user/notificationscheduler/node_modules/node-schedule/lib/schedule.js:369:11)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
The mysql server is running locally and I tried connecting and running the same query with the scheduler user successfully.
Has anyone had any experience with these modules and what could be the cause of the problem?
Many thanks

Yes, this is because of asynchronous engine v8. When your call:
db.select(connection, 'SELECT * from notifications')
It won't wait until query is finished and result are returned. This was handling by your callback, but instead of it your are closing the connection with db and query hits an error. You need to close connection in select, if you want to correct behavior:
select: function(connection, queryString){
console.log('Executing database query...');
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].messagetext);
connection.end(); // Here close the connection
return rows;
});
},

Related

NodeJS (Express) with MySQL - How to handle connection resets?

I'm running my website with NodeJS, I'm using the Express framework.
Since MySQL is the only database type at my hosting, I went with it.
I created a db.js file:
const mysql = require('mysql');
const con = mysql.createConnection({
host: .........
user: ...........
password: ............
database: ............
});
con.connect(function(err) {
if (err) {
//throw err;
console.error(err.message);
} else {
console.log('Connected Ro MySQL!');
}
});
module.exports = con;
And I using it like:
const db = require(path.join(__dirname, 'db'));
db.query('select * from table where name = ?', request.params.id, (error, result) => {
if (error) {
response.send(error.message);
} else {
//My Render Stuffs Here
});
}
});
My website works fine however sometimes let's say once every 2 weeks there is a MySQL connection reset, I think the database not available for a minute or so for some reason, and then my website crashes, I have to manually restart NodeJS what is very annoying.
Error in the console:
node:events:355
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
[...]
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
How should I change my codes to prevent crashing? I replaced throw err; with the console.error(err.message); but it only works when I start the website, not when a connection reset happens at runtime.
Found the solution: Replace createConnection with createPool and totally remove con.connect since createPool doesn't need it. That's it, now it's not crashes when the db unavailable.

Node.js server crashes after MySQL connection ends

I have a Node.js server that is hosting my webpage. I have recently set up a MySQL server and created a connection to the server. When accessing a certain page, it queries the SQL database.
My problem is that if I query the DB, it makes the connection just fine, but it will crash a little later when the server automatically closes the connection. I then tried to use con.end() after the query, but this crashes the second I access the DB. It throws the error below:
at Protocol._validateEnqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:203:16)
at Protocol._enqueue (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:138:13)
at Connection.query (/home/pi/Documents/node_modules/mysql/lib/Connection.js:200:25)
at Handshake.con.connect (/home/pi/Documents/PageDB.js:26:9)
at Handshake.<anonymous> (/home/pi/Documents/node_modules/mysql/lib/Connection.js:502:10)
at Handshake._callback (/home/pi/Documents/node_modules/mysql/lib/Connection.js:468:16)
at Handshake.Sequence.end (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
at Handshake.Sequence.OkPacket (/home/pi/Documents/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)
at Protocol._parsePacket (/home/pi/Documents/node_modules/mysql/lib/protocol/Protocol.js:278:23)
at Parser.write (/home/pi/Documents/node_modules/mysql/lib/protocol/Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
Close the database connection.
It seems to me that this is caused by the query executing after the con.end() runs. Can someone help me figure out a way to call the end function after the callback has returned with the SQL query data? Or otherwise, have my web server not crash when the connection to the DB is closed automatically? I'm open to either one. Thanks!
Code for the Node.js server is below:
//Create a connection to the db
const con = mysql.createConnection({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test',
});
router.get('/products',(req,res)=>{
con.connect((err) => {
if(err){
console.log('Error relating to connection: ' + err);
return;
}
console.log('Connection established');
con.query('SELECT * FROM ProductList',(err,rows,fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});
con.end(function(err) {
if (err) {
return console.log('error:' + err.message);
}
console.log('Close the database connection.');
});
});
Your problem is that you're con.end is being called right after you connect method. As JS is asynchronous, so it will not wait for connect to end and then continue to end instead it will call connect and put the callback on the event queue and continue to next statement where you are closing your connection. So, what you should do is move your end statement inside the callback. Try using the following code
//Create a connection to the db
const con = mysql.createConnection({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test',
});
router.get('/products', (req, res) => {
con.connect((err) => {
if (err) {
console.log('Error relating to connection: ' + err);
return;
}
console.log('Connection established');
con.query('SELECT * FROM ProductList', (err, rows, fields) => {
if (!err) {
res.send(rows);
con.end(function(err) {
if (err) {
return console.log('error:' + err.message);
}
console.log('Close the database connection.');
});
} else
console.log(err);
})
});
});

why do i get an error connection in nodejs - mysql (trying remote connection)

I recently started learning Nodejs to connect to MySQL and i'm having connection issues. I tried using putty to connect and i'm able to do so without any issues
this is my example.route.js file
const express = require('express'),
router = express.Router(),
mysql = require('mysql');
var connection = mysql.createConnection({
host: <ipaddress>,
port: <default Port>,
user: 'root',
password: <given password>,
database: <db name>,
connectionTimeout: 30000
});
connection.connect((error) => {
if (error) {
console.log('error connecting: ' + error);
} else {
console.log('Connected to server');
}
});
connection.query('SELECT * FROM test', function(err, results, fields) {
console.log('results in table: ' + results);
console.log('fields in table: ' + fields); // -1
connection.release();
if (err) throw error;
});
connection.end();
module.exports = router;
i get the following error => Error: connect ECONNREFUSED (Will update with complete error in a few hours)
As i mentioned before i used PUTTY in order to make sure there was an issue when connecting but i was able to connect to the given database name, host with the same user and password.
Not sure if this helps is an ubuntu server with MySQL
Anyone has an idea of why i'm getting the connection error? I would appreciate it the help

How do I connect local nodeJS server with MySQL which is running on AWS?

Here is my code to connect with MYSQL, I am getting connection timeout error :
This is my connection file to connect with MYSQL :
/*
* #sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/
var mysql = require('mysql');
var sqlConnection = function sqlConnection(sql, values, next) {
// It means that the values hasnt been passed
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection({
"host": process.env.dbHost,
"user": process.env.dbUser,
"password": process.env.dbPass,
"database": process.env.dbName,
"port":process.env.dbPort
});
connection.connect(function (err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err + '\n');
}
else {
console.log("Connection is available");
}
});
connection.query(sql, values, function (err) {
connection.end(); // close the connection
if (err) {
throw err;
}
// Execute the callback
next.apply(this, arguments);
});
};
module.exports = sqlConnection;
This is the error what I am getting :
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/himanshu/node_modules/mysql/lib/Connection.js:411:13)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:420:8)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
--------------------
I think I am doing something wrong in the config file which looks like, I don't know what to provide in db HOST or How actually I can connect with aws mysql db :
dbHost=00.00.000.000 // aws instance ip
dbName=HIMANSHU
dbUser=ROOT
dbPass=PASSWORD
dbPort=3360
#Himanshu Just check the Inbound rule of your Instance.
As per your code, it looks like you are running MySQL in your EC2 machine.
So just make sure, you have allowed 3306 port in your Inbound rules and outbound rules also

Node Connection Error While contacting MySql?

I wrote a connector to get the data from the mysql and when iam running the Mysql connector inside a route it is showing error and the browser is running into a infinite loop.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
//var mongoose = require('mongoose');
//Connect to Mongoose
//mongoose.connect('mongodg://localhost/malwares');
//var db = mongoose.connection()
//Connect to Mysql
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.150.94',
user : 'root',
password : 'negalkgkgkal',
database : 'dbnamehere'
});
connection.connect();
//connection.query('SELECT * from detection', function(err, rows, fields) {
//if (!err)
//console.log('The solution is: ', rows);
//else
// console.log('Error while performing Query.');
//});
//connection.end();
//Mysql connection ends
app.get('/' , function(req ,res){
res.send('Goto /api/malware for detection results');
});
app.get('/malwares' , function(req , res){
console.log('Hello');
connection.query('SELECT * from rest', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
});
connection.end()
app.listen(3000);
console.log('Listening on port 3000');
Error Log
Listening on port 3000
Hello
Error while performing Query.
And also the browser is not responding after this.
I even tried using node-inspector it gave me error like this protocol-enqueue-after-fatal-error-in-node-mysql
Any suggestions on how to solve this error?
P.S :: Database is there and also the table exists,for this purpose of error debugging i have queried another table which i commented in the code and it ran succesfully.
Error:
{ Error: Cannot enqueue Query after invoking quit.
at Protocol._validateEnqueue (/var/www/Rest/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/var/www/Rest/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Connection.query (/var/www/Rest/node_modules/mysql/lib/Connection.js:208:25)
at /var/www/Rest/app.js:39:13
at Layer.handle [as handle_request] (/var/www/Rest/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/Rest/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/Rest/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/Rest/node_modules/express/lib/router/layer.js:95:5)
at /var/www/Rest/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/Rest/node_modules/express/lib/router/index.js:335:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
If I am not mistaken you don't need connection.connect() part if connection is defined in same file (like you have), you try commenting out that line and then run it.
I know, I encountered some problems because of that