0

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?

1 Answer 1

1
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;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.