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:
1 | npm install mysql |
2. Require the mysql module in your Node.js code:
1 | const mysql = require( 'mysql' ); |
3. Create a new PoolCluster object:
1 | const poolCluster = mysql.createPoolCluster(); |
4. Add one or more pools to the PoolCluster object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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:
1 2 3 4 5 6 7 8 9 10 | 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:
1 | 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.