Connection between node and mysql crash

I have a connection between Node and MySQL with a external database:

const connectionDB = mysql.createConnection({ host: '178.129.145.252', port: 3306, user: '', password: '', database: '*****' })

when I execute my script to start it runs and I can view the users in a table, but later it crashes enter image description here anyone knows how can I connect with the external database? Thanks

Upvotes: 0

Views: 154

Answers (1)

AvyChanna
AvyChanna

Reputation: 336

Your code does not properly handle connection loss to MySQL server.

A quick solution would be to use connection pool.

var db_config = {
    host: 'localhost',
    user: 'username',
    password: 'password',
    database: 'example'
};
let pool = mysql.createPool(dbConfig);
pool.on('connection', function (conn) {
    if (conn) {
        logger.info('Connected');
    }
});

// DO SOMETHING HERE
// pool.query('QUERY GOES HERE', (err, rows) => { /* Handle query response */});

Upvotes: 1

Related Questions