Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way to change database in existing connecction with node-mysql

I am trying to change database in an existing connection in node. The connection may or may not have database name in createConnection call. Here's the code:

var mysql = require('mysql');


connection = mysql.createConnection( {
    host               : 'localhost',
    user               : 'me',
    password           : 'secret',
    port               : 3306,
    /* database           : 'test' // optional */
});

I am using node-mysql lib. Currently I'm closing the connection and re-connecting.

Is there any better way to do that? Similar to mysql_select_db in php?

like image 301
Mukesh Soni Avatar asked Apr 09 '15 04:04

Mukesh Soni


1 Answers

You can change some of the connection parameters* with the changeUser method:

connection.changeUser({database : 'my_database'}, function(err) {
  if (err) throw err;
});

*List of these parameters:

  • user: The name of the new user (defaults to the previous one).
  • password: The password of the new user (defaults to the previous one).
  • charset: The new charset (defaults to the previous one).
  • database: The new database (defaults to the previous one).
like image 152
Veve Avatar answered Nov 14 '22 22:11

Veve