How can I switch the database after connecting to MySQL in nodejs using connection pool?
I used to use the normal connection with MySQL since it has some issue now I
I suggest giving the pooling documentation a thorough read.
You've said you're using conn.changeUser(/*...*/)
, but then you've said you're using const conn = mysql.createPool(/*...*/);
to initialize that conn
constant. That means conn
is a pool, not a connection; it's not surprising that it doesn't have a changeUser
method.
If you want to change database, you need to do it on the connection, not the pool. Instead of using the shorthand pool.query
form, you'd do pool.getConnection
/conn.changeUser
/conn.query
/conn.release
. First, call your variable pool
, not conn
:
const pool = mysql.createPool({
then
pool.getConnection(function(err, conn) {
if (err) {
// handle/report error
return;
}
conn.changeUser({
database: req.session.dbname
}, function (err) {
if (err) {
// handle/report error
return;
}
// Use the updated connection here, eventually
// release it:
conn.release();
});
});
That said, if it were me, I'd be more comfortable having a connection pool per database, rather than a common pool where you change the database. That could be pure paranoia on my part, but it's what I'd do. But if you don't use separate pools, I suggest always do the changeUser
so you're sure what database you're using, or test thoroughly to see what the mysql
module does to handle this (and repeat that testing on every dot release of the module, unless the maintainer documents the behavior).