0

I'm currently developing Discord Bot, for data storing I'm using MySQL, but after some hours de connection dies. I was wondering if someone has a clue on how to do this. This the way I currently connect:

// Initalise Variables
var config;
var mysql, conn;
var fs;

try {
    // External Packages
    fs = require('fs');
    config = require('./config.json');
    mysql = require('mysql');

    // Connection Setup
    conn = mysql.createConnection({
        host: config.mysql.host,
        user: config.mysql.user,
        password: config.mysql.password,
        database: config.mysql.database
    });
    conn.connect();
} catch (e) {
    console.error(e);
}
Itsmoloco
  • 31
  • 1
  • 9
  • Possible duplicate of [How do I create a MySQL connection pool while working with NodeJS and Express?](https://stackoverflow.com/questions/37102364/how-do-i-create-a-mysql-connection-pool-while-working-with-nodejs-and-express) – Nitishkumar Singh May 27 '18 at 17:27

2 Answers2

0

You can try changing the timeout setting else if would default to 10000ms or 10 seconds.

try {
    // External Packages
    fs = require('fs');
    config = require('./config.json');
    mysql = require('mysql');

    // Connection Setup
    conn = mysql.createConnection({
        host: config.mysql.host,
        user: config.mysql.user,
        password: config.mysql.password,
        database: config.mysql.database,
        connectTimeout: config.mysql.timeout //1000000 some large number 
    });
    conn.connect();
} catch (e) {
    console.error(e);
}

You should probably use a connection pool instead of a single DB connection (this doesn't seem to have always keep alive type of setting, and you would have to give a large timeout like above)

    try {
        // External Packages
        fs = require('fs');
        config = require('./config.json');
        mysql = require('mysql');

        // Connection Setup
        conn = mysql.createConnection({
            host: config.mysql.host,
            user: config.mysql.user,
            password: config.mysql.password,
            database: config.mysql.database,
            connectionLimit: 10,
            queueLimit: 20
        });
var pool = mysql.createPool(config);

var queryDB = function(qry, cb) {
    pool.getConnection(function(error, connection) {
        if(error) {
            cb(error, null);
        }
        else {
            connection.query(qry, function (e, rows) {
                connection.destroy();
                cb(e, rows);
            });
        }
    });
-1

I think you need to install forever and start the service again. Forever is a simple CLI tool for ensuring that a given script runs continuously. Once you install forever and run the node js file then it will keeps the file alive continuously. Using npm you can install forever

npm install forever -g

Then just restart the js file

Ex:

forever start app.js

Hope now the js serves continously without breaking the connection.