#Can't add new command when connection is in closed state

2 messages · Page 1 of 1 (latest)

winged elk

A function that calls to my db


async function checkIfCountingChannelWithChannel(guildId, channelId) {
  let connection;
  try {
    const pool = getPool();
    connection = await pool.getConnection();
    let [rows] = await connection.query(`
      SELECT *
      FROM counting_channel
      WHERE guild_id = ? AND channel_id = ?`, [guildId, channelId]
    );
    return rows[0];
  } catch (error) {
    console.error('Error while trying to get a counting channel', error);
    throw error;
  } finally {
    if (connection) {
      try {
        connection.release();
      } catch (releaseError) {
        console.error('Error releasing MySQL connection:', releaseError);
      }
    }
  }
}

module.exports = checkIfCountingChannelWithChannel;``` 


The connect.js function

require('dotenv').config();
const mysql2 = require('mysql2/promise');

let pool;

const createPool = () => {
return mysql2.createPool({
connectionLimit: 20,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
};

const getPool = () => {
if (!pool) {
pool = createPool();

// Handle connection errors and attempt to reestablish the pool
pool.on('error', (err) => {
  console.error('MySQL pool error:', err);
  // Attempt to reconnect on pool error
  if (err.code === 'PROTOCOL_CONNECTION_LOST') {
    console.log('Attempting to reconnect MySQL pool...');
    pool = createPool();
  } else {
    console.error(`err:`, err) // Throw any other errors for unhandled exceptions
  }
});

}
return pool;
};

module.exports = {
getPool,
};```

error im getting is Can't add new command when connection is in closed state

Yes, My connections close every 60 seconds due to my nextjs application creating alot of them. any fixes?

atomic starBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!