我想连接两个数据库,因为一个数据库用于登录,而其他数据库用于获取登录用户的数据。
我创建了两个数据库连接,如下所示,但它覆盖了以前的连接
var express = require('express');
var path = require('path');
var AWS = require('aws-sdk');
var connection = require('express-myconnection');
//second connection
var myConnection = require('express-myconnection');
var mysql = require('mysql');
var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
app.use(
connection(mysql,{
host: 'localhost',
user: 'user1',
password : 'pass1',
port : 3306, //port mysql
database:'database1'
},'pool') //or single
);
app.use(
myConnection(mysql,{
host: 'localhost',
user: 'user2',
password : 'pass2',
port : 3306, //port mysql
database:'database2'
},'pool') //or single
);
答案 0 :(得分:2)
确定! 为了连接第二个数据库,我使用了包含池的mysql连接器文件并将其分配给变量" newConnection" :
var express = require('express');
var path = require('path');
var AWS = require('aws-sdk');
var connection = require('express-myconnection');
var mysql = require('mysql');
var app = express();
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
app.use(
connection(mysql,{
host: 'localhost',
user: 'user1',
password : 'pass1',
port : 3306, //port mysql
database:'database1'
},'pool') //or single
);
var newConnection = mysql.createPool({
host: 'localhost',
user: 'user2',
password : 'pass2',
port : 3306,
database:'database2'});
app.set('connection_user',newConnection);//setting DB configuration in a variable
稍后您可以简单地将连接器包含在另一个文件中,我们可以将其称为webservice.js:
var connection_user = request.app.get('connection_user');
connection_user.getConnection(function(){});
现在使用" connection_user"变量我们连接到第二个数据库。 希望你明白了!