node mysql connection.connect does not work - mysql

Having an odd issue with node mysql. I am running a mysql container (docker) on my local machine with a standard setup. I am able to get past mysql.createConnection, but my code always fails at connection.connect. MySQL Error logs on the container show no attempted/failed connections, and I can connect via Workbench. Has anyone had this experience trying to connect to MySQL via node.
router.get('/page', function(req,res){
const msg = 'My Query from config, tested and confirmed on Workbench';
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'user',
password : 'pw',
database : 'db',
port : 3306,
debug : true
});
console.log('Connect to server', connection.state); //Doesn't get past this guy
connection.connect(function(err) {
if (err) {
console.log('error connecting: ' + err.stack);
return err;
}
else {
console.log('connected as id ' + connection.threadId);
}
});
middleware.logger.debug('Make Query');
connection.query(msg, function(err, rows, fields) {
if (!err) {
console.log('The solution is: ', rows);
res.json('We got some rows!');
}
else {
console.log('Error while performing Query.', err);
res.json(err);
}
});
console.log('End Connection');
connection.end();
});
Also, should note: I get the same error whether my docker container is running or not.
EDIT: Okay, want to amend my problem, this is actually an issue with express router. Expanded code above.

Related

How to monitor mysql connection status in node?

So this is from https://www.npmjs.com/package/mysql,
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
there're 2 parts confuse me,
is connection.connect() making the real connection ? i see it's checking for error. But what happens if everything is ok, but i turn off mysql server after 5 minutes, how to monitor the status pls ?
Even for pool events, i don't see the disconnect event.
for the above code, is there a async/await version for connection.connect() ?
Thanks !
connection.connect is sync you can use it after connection. To handle connection errors you can use:
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
By the way everything is explained in node-mysql read me

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

Node.js mysql query response delay

I am using node.js mysql driver. But when the server under high load, i guess mysql is doing queue for queries. How can I prevent this? I want to do query instantly.
How can I resolve this? My queries are laggy.
My code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'ip',
user : 'db',
password : 'pass'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.query('USE db');
connection.query({ sql:"select token,COUNT(token) as sayim from tokens where username=? or anon=?", timeout: 10000},[data,data],function(err,info) {
if (info[0].sayim != 0) {
callback(info[0].token);
}else{
callback("0");
}
});
Ps: The server is not returning any error for this. But when I do a query, server is responding after approximately 10 seconds. If server is not under the high load it is responding instantly.
You could use PoolConnection instead.
var connection = mysql.createPool({
host : 'ip',
user : 'db',
password : 'pass',
database : 'db'
});
Another thing that comes to mind: In your example, you use asynchronous functions one after the other which should cause you some troubles as well.

No hint of errors when trying to connect to a database

I've been struggling to get MySQL working with node for a while. When I run the following code no errors are thrown, but simultaneously none of the console messages are being printed (except for the obvious one).
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '******',
database : 'blogDB'
});
connection.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
}
console.log('Connected to the database');
});
var queryString = 'SELECT * FROM blogs';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Post: ', rows[i].id);
}
});
connection.end();
http.listen(3306, function(){
console.log('listening on *:3306');
});
Output:listening on *:3306
On top of this, when I go to "localhost:3306" in the browser, a download is immediately started and nothing appears on the web page. The download is a file with no extensions, but contained the following:
J
5.6.19 tscvKP3M ÿ÷ € g?F!q6X:Y2*z mysql_native_password ! ÿ„#08S01Got packets out of order
I am not sure if that is relevant, but it certainly was not happening when I was not running MySQL. I have no idea how to troubleshoot this. Any ideas what could be going wrong?
The error here is you're coding node.js as if it were procedural. It's not.
connection.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
}
console.log('Connected to the database');
var queryString = 'SELECT * FROM blogs';
//change from connection to "this" because you're inside the context of the connection object now
this.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Post Titles: ', rows[i].id);
}
});
});
Node.js uses a series of callbacks that run when a task is completed. So when you want to do something AFTER you're connected to the DB, you run that code inside the callback.
What your code is doing is attempting to connect to the database, then while attempting to connect to the database you're querying a database you're not connected to, and so on and so forth.
For sake of illustrating the principle a little more, node functions use the following general methodology.
//1
myObj.myFunc( function( err , foo , bar ) {
//A
});
//2
myObj.myOtherFunc( function( err , someVar ) {
//B
});
1 will always run before 2. A and B may run in either order depending on when 1 and 2 finish executing. A will always run after 1 is done. B will always run after 2 is done.
Hopefully that helps clear things up ;)
As it turns out, MySQL and the app were running using the same port (3306). Changing the app's port to 3307 did the trick.