how connect a mysql connection after destroy it in node js - mysql

my code is this(It's about like this):
this.con = mysql.createConnection({...});
this.con.connect(); // No error
this.con.destroy();
.......
.......
this.con.connect(); // error: Cannot enqueue Handshake after being destroyed.

Try to re-create/re-assign the connection before connecting again:
this.con = mysql.createConnection({...});

Related

Failing to connect to MySQL in Dlang with vibe-d and mysql-native

I have simple vibe-D program which is trying to connect to SQL:
import std.stdio;
import mysql;
import vibe.d;
void main()
{
MySQLPool db_pool = new MySQLPool("localhost","root","","dbname",3306);
Connection db = db_pool.lockConnection();
// same thing happens with:
// string connectionStr = "host=localhost;port=3306;user=root;db=dbname";
// db = new Connection(connectionStr);
}
(I deleted everything else for simplification)
Dependencies:
"dependencies": {
"mysql-native": "~>3.2.0",
"vibe-d": "~>0.9.4"
}
And it fails to connect with:
object.Exception#../../../.dub/packages/vibe-core-1.22.4/vibe-core/source/vibe/core/net.d(256): Failed to connect to [0:0:0:0:0:0:0:1]:3306: refused
When I try it without vibe-d in the dub project (using phobos sockets) it connects with no problem. What am I doing wrong?
that's an ipv6 address.... is your mysql listening on that interface? might help trying 127.0.0.1 instead of localhost and seeing what happens.
can also consider reconfiguring mysql to listen on all interfaces too, including the ipv6

Error: Cannot enqueue Query after fatal error. Expressjs. Mysql

I have my Express js connect to multiple dbs. Which works everytime I startup my app. But As soon as my connection to my database goes stale... the connection returns an error code of PROTOCOL_CONNECTION_LOST. Which is normal for a mysql when a connection is idle. My mysql server is deployed in AWS RDS which also works just fine.
The problem is, everytime my express app encounters the PROTOCOL_CONNECTION_LOST error, it should reconnect to the database, which in fact also works. BUUT when I try to make queries to my MYSQL db. It returns a Error: Cannot enqueue Query after fatal error. error. I've been dealing with this for a while, and my workaround is to restart the express app everytime. hope someone else has encountered this and could give an advice.
Here is my sample code for connecting to db:
var mysql = require('mysql');
var mysqlConn
// mysqlConn.connect();
function handleDisconnect() {
mysqlConn = mysql.createConnection({
host: 'aws_instance***',
user: '******',
password: '*****',
database: 'my_db',
multipleStatements: true
});
mysqlConn.connect(function (err) {
if (err) {
console.log('ERROR CONNECT admin:', err.code + '--' + err.address);
setTimeout(handleDisconnect, 2000);
} else {
console.log('Connected to DB')
}
});
mysqlConn.on('error', function (err) {
console.log('ERROR admin', err.code + '--' + err.address);
if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
console.log("Connection to db lost!")
handleDisconnect(); // lost due to either server restart, or a
} else {
console.log(err) // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
module.exports = {
mysqlConn: mysqlConn,
};
Then here is my output logs as shown in my server logs.
ERROR db PROTOCOL_CONNECTION_LOST--undefined
Connection to db lost!
Connected to db
OPTIONS /verify-token/ 200 0.285 ms - 4
Error: Cannot enqueue Query after fatal error.
POST /verify-token/ 500 1.332 ms - 95
OPTIONS /auth/login 200 0.793 ms - 4
Error: Cannot enqueue Query after fatal error.
POST /login 500 1.564 ms - 58
OPTIONS /login 200 0.687 ms - 4
Error: Cannot enqueue Query after fatal error.
POST /login 500 1.467 ms - 58
While there are workarounds, they apparently don't work for everyone. The suggestion in the documentation is to use connection pooling instead of manually managing individual connections.

Simple React with mySql fails to read table records

I created a React project by entering the following command prompt commands
mkdir mysql-test && cd mysql-test
npm init –y
npm install mysql –save
Then I created a file called app.js and I put in the following code:
// app.js
const mysql = require('mysql');
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'rds-mysql-wmcw.cgz0te1dlkah.us-east-1.rds.amazonaws.com',
user: 'masterUsername',
password: 'masterPassword',
database : 'db_wmcw'
});
//try to connect to the mySql database. If an error occurs, display an
error message on the console
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
//a connection has been established to the database. Now, run a query against the table 'homepage'
//to retrieve each row and all columns of the table
console.log('Connection established');
con.query('SELECT * FROM homepage', (err,rows) => {
//if an error occurs when reading the data from the table, display the error on the console
if(err) {
console.log(err);
return;
}
//data has been retrieved from the table. display the data to the console
console.log('Data received from Db:\n');
console.log(rows);
});
});
con.end((err) => {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
Before I added the con.query command, when I type in app.js at the command prompt, the response back is Connection established. So I know that I am connecting to the mySql database. When I include the con.query command, and I type in app.js at the command prompt, I get the following error:
Connection established
{ Error: Cannot enqueue Query after invoking quit.
at Protocol._validateEnqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:203:16)
at Protocol._enqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:200:25)
at Handshake.con.connect (C:\jrs\codercamp\mysql-test\app.js:21:7)
at Handshake. (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:502:10)
at Handshake._callback (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:468:16)
at Handshake.Sequence.end (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Handshake.Sequence.OkPacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:92:8)
at Protocol._parsePacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
Right at the top of the error it states Cannot enqueue Query after invoking quit. I don't understand why the system thinks I am executing the query after invoking quit. I am not invoking quit unless that is what happens when I execute con.end but con.end is the last statement to execute. It is way after the query call.
Any assistance is greatly appreciated.
Thank you.
PS - I have included the host name, user ID, password, and database name to make debugging easier. There is no real important data in the database
Okay, so the alternative solution would be uninstall mysql package and change with mysql2 package instead. As the author said:
MySQL2 is mostly API compatible with mysqljs and supports majority of features
This answer is for the questioner's comment on his post
If you really wanna reassign the one row of data, you can do:
const { product_detail, product_description } = results[0];
That's basic syntax :D (ES6 maybe)

Close MySQL connection using node-mysql in gcloud functions?

I have hosted an application in gcloud which uses mysql. But when the function crashes (error/exceptions) I need to end the connection. When the function gets crashed the logs emits :
error: Function worker killed by signal: SIGTERM
So how can I close my mysql connection (connection.end()) before the function gets terminated ?
I don't know how you can end the connection when your app crashes. But maybe you can use mysql.createPool(...); rather then mysql.createConnection(...);
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
This way you can set pooling options for the connection and let the MySQL sort of manages the termination.

connect ECONNREFUSED - node js , sql

I have the next code in a js file:
var mysql = require('mysql');
var TEST_DATABASE = 'nodejs_mysql_test';
var TEST_TABLE = 'test';
var client = mysql.createClient({
user: 'root',
password: 'root',
});
client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {
if (err && err.number != mysql.ERROR_DB_CREATE_EXISTS) {
throw err;
}
});
But I get this error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: connect ECONNREFUSED
at errnoException (net.js:632:11)
at Object.afterConnect [as oncomplete] (net.js:623:18)
As I understand it, this is a connection problem - but how do I solve it?
( I'm working on windows 7)
Thanks!!
I know two ways to solve it:
In mysql.conf, comment skip-networking.
Try to set the socket like this:
var client = mysql.createClient({
user: uuuu,
password: pppp,
host: '127.0.0.1',
port: '3306',
_socket: '/var/run/mysqld/mysqld.sock',});
I got this error when MySQL Server was not running.
I changed my configuration via Initialize Database in MySQL.PrefPane, the System Preferences tool for MySQL on OS X - to Use Legacy Password Encryption - to fix ER_NOT_SUPPORTED_AUTH_MODE.
This config change stopped MySQL Server and then I got ECONNREFUSED when I tried to connect to MySQL from node.js.
Fixed by restarting MySQL Server from the MySQL System Preferences tool.
Try to fix your defined port in mysql and your Node.js script.
You can define the mysqld port in the *.cnf file inside the mysql directory,
and you can define that port when you connect to MySQL in your Node.js script.
Something like this in the cnf file
port = 3306