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

偶尔善良 提交于 2020-01-24 04:03:23

问题


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?


回答1:


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).



回答2:


The only way I have found is to use the 'USE' command

in your example it would look like this

let database = 'my_database';
connection.query(`USE ${database}`, (error, results, fields) => {
    ...
  });

after that all queries using this connection would be sent to the new database



来源:https://stackoverflow.com/questions/29529947/recommended-way-to-change-database-in-existing-connecction-with-node-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!