Mysql Connection timeout with Sequelize - mysql

I have a problem when making the connection to MySql in the vagrant box with Nodejs and Sequelize.
I can connect to MySql DB from Navicat or Python, Nodejs and Mysql package. But I couldn't make the connection with Nodejs and Sequelize.
Guys, Do you have any idea?
const Sequelize = require('sequelize');
const sequelize = new Sequelize('blog', 'root', null, {
host: 'localhost',
dialect: 'mysql',
operatorsAliases: false,
port: 3307,
pool: {
max: 5,
min: 0,
acquire: 40000,
idle: 20000
},
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});

Usually MySQL work on port 3306 (you are doing the request on port 3307).
For another way you can try to use MySQL package: https://github.com/mysqljs/mysql.
Best regards.

Related

How to close mySql query connection in nodejs

I am using raw mySql query for my development.
I want to close the query connection after executing the query.
What can I use as per my code?
My Connection Sample:
const Sequelize = require('sequelize')
const dotenv = require('dotenv');
dotenv.config();
const sequelize =
new Sequelize(process.env.DBNAME, process.env.DBUSER, process.env.DBPASS,
{
host: process.env.HOST,
port: process.env.HOST_PORT,
dialect: 'mysql',
operatorsAliases: 0,
timezone: "+06:00",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
}
}
)
module.exports = sequelize;
My Query sample:
const dbConnect = require('../database/db');
let getEmployeeData =
await dbConnect.query(
`Select * From employee where employeeId = '00001'`,
{type: QueryTypes.SELECT});
return res.json({data: getEmployeeData});
Before return I want to close my query connection. As I am getting error "packets_out_of_order" after idle the connection in nodejs, so I decide to test by closing the connection.
Thanks in advance...
You can try with
dbConnect.end();

Node MySQL Connection Pool - wait for database to start

How do I check if a MySQL database is ready for some queries from a Node MySQL Connection Pool?
I have a Docker environment consisting of thee containers:
container 1: web server
container 2: api
container 3: database
The database container runs a MySQL database. The api container connects to that database. All three containers are started at the same time. The web server container is up after 0,5s. The api container is up after 2s. The database server is up after 20s.
Currently, the api tries to access the tables of the database before the database is up and running. This leads to errors like connection refused. The following code segment always ends up with the message "Error querying database!" when the MySQL database is not yet up:
const sql: string = 'SELECT * FROM sometable;';
MySQL.createPool({
connectionLimit: 10,
acquireTimeout: 30000,
waitForConnections: true,
database: 'mydatabase',
host: 'localhost',
multipleStatements: true,
password: 'mypassword',
user: 'root',
}).query(sql, (err, result) => {
if (result) {
console.log('Successfully queried database.');
} else {
console.log('Error querying database!');
}
});
Versions in use:
OS: Ubuntu 19.10
Node: v13.6.0
MySQL (Node API): "#types/mysql": "2.15.8" and "mysql": "2.17.1"
MySQL (Docker Database): mysql:5.7.28
TypeScript: 3.7.4
I would like to check (and wait) the database readiness out of the api, possibly using the Connection Pool I use for queries. Is that possible?
Retry to connect with setTimeout():
(answer in Javascript rather than typescript)
'use strict';
const dbpool = require('mysql').createPool({
connectionLimit: 10,
acquireTimeout: 30000,
waitForConnections: true,
database: 'mydatabase',
host: 'localhost',
multipleStatements: true,
password: 'mypassword',
user: 'root',
});
const sql = 'SELECT * FROM sometable;';
const attemptConnection = () =>
dbpool.getConnection((err, connection) => {
if (err) {
console.log('error connecting. retrying in 1 sec');
setTimeout(attemptConnection, 1000);
} else {
connection.query(sql, (errQuery, results) => {
connection.release();
if (errQuery) {
console.log('Error querying database!');
} else {
console.log('Successfully queried database.');
}
});
}
});
attemptConnection();
Here is my test run:
$ sudo service mysql stop; node test.js & sudo service mysql start
[1] 24737
error connecting. retrying in 1 sec
error connecting. retrying in 1 sec
$ Successfully queried database.
FYI, The program never ends because it needs dbpool.end();
Your API should try to connect to the database with a timeout and a certain threshold of connection attempts. However, there are readily available solutions for this scenario.
Try using wait-for-mysql module.
waitForMy = require 'wait-for-mysql'
config =
username: user
password: pass
quiet: true
query: 'SELECT 1'
waitForMy.wait(config)
Here you have a variation but with no need to mysql pooling. I'm using this on my server and it does work:
const mysql = require('mysql')
var db // global, to use later to db.query
var dbInfo = {
host : 'example.org',
database : 'some_database',
user : 'bob',
password : 'secret'
}
function connectToDb(callback) {
const attemptConnection = () => {
console.log('Attempting to connect to db')
dbInfo.connectTimeout = 2000 // same as setTimeout to avoid server overload
db = mysql.createConnection(dbInfo)
db.connect(function (err) {
if (err) {
console.log('Error connecting to database, try again in 1 sec...')
db.destroy() // end immediately failed connection before creating new one
setTimeout(attemptConnection, 2000)
} else {
callback()
}
})
}
attemptConnection()
}
// now you simply call it with normal callback
connectToDb( () => {
console.log('Connection successfully')
// do some queries
db.query(..)
})

Connect Sequelize/Node to XAMPP Mysql

I've a working script to connect and work with Sequelize on Node.js
But now i'm trying to connect this to my MySQL database on XAMPP
MySQL Port on XAMPP: 3306
When i run node.js after i have configured the app.listen and the config of sequealize i get the following error
ERROR: listen EADDRINUSE :::3306
I've looked for but i didn't find much information about that, i don't know what i'm doing bad.
Thanks you for every answer!
app.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const { sequelize } = require('./models')
const config = require('./config/config')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
require('./routes')(app)
sequelize.sync()
.then(() => {
app.listen(config.db.options.port || 3306) // 8081 original
console.log(`Server iniciado en puerto: ${config.db.options.port}`)
})
config.js
module.exports = {
db: {
database: process.env.DB_NAME || 'intraenvios',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASS || '',
options: {
dialect: process.env.DIALECT || 'mysql', // sqlite original
host: process.env.HOST || 'localhost',
storage: './intraenvios.sqlite',
port: process.env.PORT || 3306 // 8081 original
}
}
}
EDIT:
For to connect by xampp simply, i made this:
const sequelize = new Sequelize('test', 'root', '', {
host: "127.0.0.1",
dialect : 'mysql',
operatorsAliases: false
});
sequelize.authenticate().then(function(){
console.log("sucess");
}).catch(function(error){
console.log("error: "+error);
});
Obs: operatorsAliases: false - To fix deprecated message of sequelize
Good Fun :)

Error in connecting to Mysql from nodejs

I have started node-js recently and i was trying to connect my nodejs server with mysql.
The problem is i am getting an error, i really don't know why, i am using phpmyadmin.
Phpmyadmin details
user: root
host: localhost
password is not set
This is the image of my phpmyadmin database
This is the settings of my phpmyadmin console
This is the terminal where it is showing error connecting to DB
index.js
var express = require("express");
var app = express();
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "learning",
});
connection.connect(function(err){
if(err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
console.log('3');
connection.end(function(err) {
console.log('Connection closed');
console.log('4');
process.exit();
});
});
app.listen(port,function(err1){
console.log("Listening on the port 3000");
});
connection to mysql from node js, you are use to mysql from node js connection
/config
/database.js
/server.js
/.env
const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);
server.listen(process.env.ServerPort, '0.0.0.0', () => {
logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
When you run this:
node server.js
database.js file
const My = require('jm-ez-mysql');
// Init DB Connection
const connection = My.init({
host: process.env.DBHOST,
user: process.env.DBUSER,
password: process.env.DBPASSWORD,
database: process.env.DATABASE,
dateStrings: true,
charset: 'utf8mb4',
timezone: 'utc',
multipleStatements: true,
connectTimeout: 100 * 60 * 1000,
acquireTimeout: 100 * 60 * 1000,
timeout: 100 * 60 * 1000,
});
module.exports = {
connection,
};
I had changed the port from default 3306 of phpmyadmin mysql to 3308
therefore i added port: 3308 and it started working.
var connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "learning",
port: 3308
});

NodeJS: How to use Connection Pooling with MySQL correctly? How useful it is?

I'm using connection pooling in NodeJS with MySQL. There are several connections remain in processlist in Sleep state, which results too many connection in the end even if site does not have heavy traffic.
Here is sample code as I'm using it:
var pool = mysql.createPool({
host: '127.0.0.1',
user: '***',
password: '***',
database: '****'
});
pool.getConnection(function (err, connection) {
connection.query("SELECT * from test", function (error, data) {
connection.release();
if (error) {
console.log(error);
} else {
// perform further process
}
});
});
Is connection not released at proper location? Suggest if there could be any improvement in code above.
That is what pool does, you can add connection limit...
var pool = mysql.createPool({
connectionLimit : 10,
host: '127.0.0.1',
user: '***',
password: '***',
database: '****'
});