Showing posts with label Node.js. Show all posts
Showing posts with label Node.js. Show all posts
How to create a PoolCluster in Node.js with MySQL

How to create a PoolCluster in Node.js with MySQL

To create a PoolCluster in Node.js with MySQL, you can follow these steps:

1. Install the mysql package in your Node.js project by running the following command in your terminal:

  npm install mysql
2. Require the mysql module in your Node.js code:
const mysql = require('mysql');
3. Create a new PoolCluster object:
const poolCluster = mysql.createPoolCluster();
4. Add one or more pools to the PoolCluster object:
const poolConfig1 = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database1'
};

const poolConfig2 = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database2'
};

poolCluster.add('MASTER', poolConfig1);
poolCluster.add('SLAVE', poolConfig2);

In this example, we're adding two pools to the PoolCluster object: one for the MASTER database and one for the SLAVE database.

5. Use the PoolCluster object to obtain connections from the appropriate pool:
poolCluster.getConnection('MASTER', (err, connection) => {
  if (err) throw err;

  connection.query('SELECT * FROM my_table', (error, results, fields) => {
    if (error) throw error;

    console.log(results);
    connection.release();
  });
});
In this example, we're obtaining a connection from the MASTER pool and executing a SELECT query on the my_table table.

6. Release the connection back to the pool when you're done with it:
connection.release();
That's it! You now have a working PoolCluster object that you can use to manage connections to multiple MySQL databases in your Node.js application.