1

I am using node.js npm module mysql for connection with a MySQL database.

I see there is a possibility to use:

  • either pool.getConnection(), connection.query() and connection.release()
  • or pool.query

I have two questions regarding the second scenario.

1) Is there any automatic reconnect in case of error, lost connection while using pool.query? (is 'handle disconnect' function needed while using pool?

2) Using the first approach I can set connection.on('error', function(){...}). How to do this in the second case? (pool.on('error'...) ?)

2 Answers 2

1

1) Correct me if I'm wrong, but I don't think there's a method for auto connection upon disconnect while using pool query. It's a good code design to let us know the error, and let us decide what to do upon disconnect.

2) We can use pool.getConnection((err, con) => {})

Here's the code I'm using to check for connection before running a query. Hope it helps.

connect: function ()
    {
        return new Promise((resolve, reject) => {
            let pool = Mysql.createPool({
                connectionLimit: config.mysql.connectionLimit,
                host: config.mysql.host,
                user: config.mysql.user,
                password: config.mysql.password,
                database: config.mysql.database
            });

            pool.getConnection((err, con) =>
            {
                try
                {
                    if (con)
                    {
                        con.release();
                        resolve({"status":"success", "data":"MySQL connected.", "con":pool});
                    }
                }
                catch (err)
                {
                    reject({"status":"failed", "error":`MySQL error. ${err}`});
                }
                resolve({"status":"failed", "error":"Error connecting to MySQL."});
            });
        });
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You can setup the pool connection like this :

const mysql = require("mysql2");

const pool = mysql.createPool({
    host: "localhost",
    port: 3306,
    user: "root",
    password: "password",
    database: "test",
  }).promise();

 //test the connection
(async () => {
  try {
    const connection = await pool.getConnection();

    console.log("Database connected successfully");

    // Release the connection back to the pool
    connection.release(); 

  } catch (error) {
    console.error("Database connection error : ", error);
  }
})();

module.exports = pool;

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.