Facing issue with mysql database with node js - mysql

i have created express app with mysql database.
when i call mysql query it works fine and then i call my view. loading view take few minute(2-3 min) and app crashed with bellow error.
events.js:287
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:310:20)
at Protocol.EventEmitter.emit (domain.js:482:12)
at Protocol._delegateError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (events.js:310:20)
at Socket.EventEmitter.emit (domain.js:482:12)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
[nodemon] app crashed - waiting for file changes before starting...
i already spend 8- 10 hours.
please help me to resolve this issue.
thanks
Update:
const options = {
user: config.get('MYSQL_USER'),
password: config.get('MYSQL_PASSWORD'),
database:config.get('DATABASE'),
host: config.get('HOST'),
port: 3306
}
const connection = mysql.createConnection(options);
connection.connect( function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:"); throw err;
} else {
console.log("Connection established.");
}
});

use below
const options = { connectionLimit :10, user:config.get('MYSQL_USER'), password: config.get('MYSQL_PASSWORD'), database:config.get('DATABASE'), host: config.get('HOST'), port: 3306 }
const connection_pool = mysql.createPool(options);
connection_pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
provide connectionLimit according to you use this is pool size of connection

Related

The mysql server disconnects every night, how do I resolve it?

I leave my computer on 24 hours, but I still lose connection with the MySQL server. My WiFi runs smoothly and is never disconnected because I'm still able to use the internet along with my other electronics. The error message says
The server closed the connection.
Is this inferring a problem on my computer/connection or with MySQL? Or is it my codes? Please advise.
Error messages:
events.js:174
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:97:28)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:525:10)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at Connection._handleProtocolError (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:426:8)
at Protocol.emit (events.js:198:13)
at Protocol._delegateError (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:97:28)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:63:19)
My codes:
let con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: 'db',
dateStrings: 'date',
});
const handleDisconnect = () => {
con.connect(err => {
if (err) throw err;
console.log("Connected!");
});
con.on('err', err => {
console.log('db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();

How to provide SERVICE_NAME in the connection options in mysql npm?

I have a JDBC connection string something like this
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=OFF)(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=1711))(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=1712)))(CONNECT_DATA=(SERVICE_NAME=servicename)(SERVER=DEDICATED)))
I have created the connection as
var connection = mysql.createConnection({
host: "hostname",
port: "1711",
user: "user",
password: "password"
});
How do I also provide SERVICE_NAME (like the jdbc string) to the connection options?
I am getting the following error without it:
Error: connect ECONNREFUSED <some_ip>:1711
at Object.exports._errnoException (util.js:1028:11)
at exports._exceptionWithHostPort (util.js:1051:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
--------------------
EDIT:
Changing the port to 1712 gives me a different error after taking a lot of time.
Error: Connection lost: The server closed the connection.
at Protocol.end (..\node_modules\mysql\lib\protocol\Protocol.js:113:13)
at Socket.<anonymous> (..\node_modules\mysql\lib\Connection.js:109:28)
at emitNone (events.js:91:20)
at Socket.emit (events.js:186:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
EDIT: Sorry. I didn't see the database was oracle and started trying mysql directly.
I am assuming that your mysql server is running on port 1711 not default port.
And if you are getting Connection lost error mean there are something wrong on your network try to reconnect your server after sometime.
var conn;
function handleDisconnect() {
conn = mysql.createConnection(//your config);
conn.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
setTimeout(handleDisconnectConnection, 5000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnectConnection();
} else {
throw err;
}
});
}
handleDisconnectConnection();
Hope that will work for you

Node and MySQL connection to database

I need t o provide the MySQL connection for modules, so I provide the code like this:
var express = require('express');
var mysql = require('mysql')
var app = express();
var connection = mysql.createConnection({
host: '149.xxx.xx.x',
user: 'User',
password: 'Password',
database: 'DataBase',
port: 1443,
});
connection.connect(
function(error) {
console.log(error.code); // 'ECONNREFUSED'
console.log(error.fatal); // true
console.log(error.sql);
console.log(error.sqlMessage);
}
);
and after some time (about 1-2 minutes) I received an error from those console.logs:
ECONNRESET
true
undefined
undefined
I think maybe it's the timeout because of my "nonactivity", but when I'm trying to do the query the errors are the same.
Have any idea what is wrong? I checked it from DataGrip and the data are correct.
Ok, I found one small bug here. The database is MS SQL Server (microsoft). I'm trying now using the library called mssql to connect to that database, provide some code:
var config = {
server: "149.xxx.xx.x",
database: "Database",
user: "User",
password: "Password",
connectionTimeout: 300000,
requestTimeout: 300000,
pool: {
idleTimeoutMillis: 300000,
max: 100
}
};
function getEmp() {
var connection = new sql.Connection(config);
var req = new sql.Request(connection);
connection.connect(function (error) {
if(error) {
console.log(error);
return;
}
req.query('Procedure', function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
connection.close();
});
});
}
getEmp();
and I receive the error:
{ ConnectionError: Failed to connect to 149.xxx.xx.x:1433 - connect ETIMEDOUT 149.xxx.xx.x:1433
at Connection.<anonymous> (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/mssql/lib/tedious.js:353:25)
at Connection.g (events.js:292:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.socketError (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/tedious/lib/connection.js:791:12)
at Socket.<anonymous> (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/tedious/lib/connection.js:33:15)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
name: 'ConnectionError',
message: 'Failed to connect to 149.xxx.xx.x:1433 - connect ETIMEDOUT 149.xxx.xx.x:1433',
code: 'ESOCKET' }
For sure the data are correct- DataGrip is connecting fine here.
I found at google the similar problem, the problem was Disabled TCP/IP. I checked this one and it's Enabled with this port 1443.

Connection timed out when using connection pooling

I get the following error when I get a connection object from a connection pool. It works sometimes but sometimes I get an error and the connection is undefined. I don't think I am supposed to get a connection timeout error because I'm using connection pool and in a connection pool you already have a few connections and you're not creating a new connection.
Can someone tell me how to handle this error and connect again.
The error at getConnection
{ [Error: connect ETIMEDOUT]
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }
The code:
var pool = mysql.createPool({
connectionLimit : 100, //important
host : '192.168.2.2',
user : 'testmysql',
password : 'test123',
database : 'tollsystem',
debug : false
});
I get the error here while using the pooled object:
app.get('/getClientList',function(req,res){
var data={
"error":1,
"clients":""
};
pool.getConnection(function(err,connection){
console.log(err);
connection.query("select * from mstrclient",function(err,rows,fields){
if(rows.length !=0){
res.json(rows);
}else{
data["error"]=1;
data["clients"]="no details found";
res.json(data);
}
connection.release();
})
});
});
The error:
connection.query("select * from mstrclient",function(err,rows,fields){
^
TypeError: Cannot read property 'query' of undefined
at D:\abhilash\Projects\Toll main aHosted\TollMain\server.js:415:15
at Handshake.onConnect (D:\abhilash\Projects\Toll main aHosted\TollMain\node
_modules\mysql\lib\Pool.js:58:9)
at Handshake.Sequence.end (D:\abhilash\Projects\Toll main aHosted\TollMain\n
ode_modules\mysql\lib\protocol\sequences\Sequence.js:85:24)
at D:\abhilash\Projects\Toll main aHosted\TollMain\node_modules\mysql\lib\pr
otocol\Protocol.js:399:18
at Array.forEach (native)
at D:\abhilash\Projects\Toll main aHosted\TollMain\node_modules\mysql\lib\pr
otocol\Protocol.js:398:13
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)

node-mysql implodes without doing anything

I am trying to simply connect to a mysql db, then close the connection. My code is basically taken straight from node-mysql's guide.
require('fs').readFile('/etc/mysql/mysql-ssl-ca-cert.pem','utf8',function(err,caFile){
if(err){
console.error(err);
}else{
var connection = require('mysql').createConnection({
host : 'localhost',
user : 'root',
password : 'password',
ssl : { ca : caFile }
});
connection.connect(function(err){
if(err){
console.error(err);
}else{
console.log('connected');
}
});
connection.end(function(err) { if(err) console.error('Error On DB Close.'); });
}
});
I get the 'connected' message but then everything crashes, triggered by an uncaught error exception, what did I do wrong?
backtrace:
events.js:85
throw er; // Unhandled 'error' event
^
Error: shutdown ENOTCONN
at exports._errnoException (util.js:746:11)
at Socket.onSocketFinish (net.js:232:26)
at Socket.emit (events.js:104:17)
at finishMaybe (_stream_writable.js:484:14)
at endWritable (_stream_writable.js:493:3)
at Socket.Writable.end (_stream_writable.js:459:5)
at Socket.end (net.js:407:31)
at Protocol.<anonymous> (/Users/camdennarzt/Developer/JS/barcoding/node_modules/mysql/lib/Connection.js:85:27)
at Protocol.emit (events.js:129:20)
at Protocol.end (/Users/camdennarzt/Developer/JS/barcoding/node_modules/mysql/lib/protocol/Protocol.js:99:10)
Turned out to be a bug in node or node-mysql. See https://github.com/felixge/node-mysql/issues/1027