NodeJS MySQL connection string

2019-05-07 20:10发布

问题:

I created ExpressJS MVC app using MySQL as DB with Yeoman generator and in config.js I want to change MySQL connection strings, but I don't know to specify password in string.

my string is mysql://root@localhost:3306/

Please help me.

回答1:

Password and DB name also a part of connection string.
Ex: mysql://root:password@localhost:port/dbName



回答2:

Maybe you can try something like this:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'YOURPASSWORD',
  database : 'YOURDATABASE'
});

Take a look at this tutorial.

If this doesn't work, you should provide us with more information.



回答3:

Here's generic connection-string parser, which offers a flexible optional syntax, while adhering to the URL syntax. Works in any environment.

var ConnectionString = require('connection-string');
var obj = new ConnectionString('my-server:12345');


回答4:

I suggest using knex. Setting up a connection pool that manages your pool for you is trivial. See the documentation.

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host     : '127.0.0.1',
    user     : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});