LoboMetalurgico
LoboMetalurgico

Reputation: 17

Node MYSQL Connection lost: The server closed the connection

I'm creating a bot for discord that has a connection to mysql. So far, it was working normally but after changing the server where I host the mysql server (it was always remote), it started giving this error:

Error: Connection lost: The server closed the connection.

The code where I run the query and create the connection to the server is this:

  const connection = mysql.createConnection({
    host: config.host,
    user: config.dbUser,
    password: config.dbPassword,
    database: config.database
  });

  connection.connect(function(err) {
    if (err) {
      console.error("[MYSQL] Error: " + err.stack);
      return;
    }

    console.log("[MYSQL] Connected with ID " + connection.threadId + "!");
  });

  function query(sql) {
    return new Promise(resolve => {
      connection.query(sql, function(error, result, fields) {
        if (error) return error;
        const analise = JSON.stringify(result[0]);
        const final = JSON.parse(analise);
        resolve(final);
      });
    });
  }

  exports.connection = connection;
  exports.query = query;

Can someone help me?

Upvotes: 0

Views: 493

Answers (1)

Ahmed ElMetwally
Ahmed ElMetwally

Reputation: 2393

const mysql = require('mysql2');

const myDB = mysql.createPool({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  port: process.env.MYSQL_PORT,
  database: process.env.MYSQL_DB_NAME,
});

const queryConstructor = pool => (query, args = []) =>
  new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        return reject(err);
      }
      connection.query(query, args, (err, results) => {
        connection.release();
        if (err) {
          return reject(err);
        }
        resolve(results);
      });
    });
  });

const query = queryConstructor(myDB);

query('SELECT 1 + 1')
  .then(console.log)
  .catch(console.error);

module.exports = query;

Upvotes: 1

Related Questions