简体   繁体   中英

Node Express Multiple SQL server Connection

I need to connect to diferent databases on direfent servers. The servers are Microsoft SQL Server.

I do it like this:

dbconfig.js

    var sql1 = require('mssql')
    var sql2 = require('mssql')

    var conn1 = {server:"SERVER IP", database:"db1", user:"foo", password:"foo", port:1433}

    var conn2= {server:"SERVER2 IP", database:"db2", user:"foo2", password:"foo2", port:1433}

var server1= sql1.connect(conn1)
    .then(function() {  debug('Connected'); })
    .catch(function(err) { debug('Error connect SQL Server', err);  });

    var server2= sql2.connect(conn2)
        .then(function() {  debug('Connected'); })
        .catch(function(err) { debug('Error connect SQL Server', err);  });

module.exports = {"ServerConn1": sql1, "ServerConn2": sql2};

After that, both connection are active, but when I do a query to the first connection it didn't work.

The error is Invalid object name 'FooDatabase.dbo.fooTable'.

Can anyone help me to solve this issue?

Thanks!

I implement using MySQL you can do the same thing mssql by passing empty database parameter and letter update database before creates connection.

And you do not need to import two-times just update the DB name before creating connection or query.

const express = 

require('express');  
const app = express();  
const port = process.env.PORT || 80;
var http = require('http');
var mysql = require('mysql')
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',//here i am not passing db and db is undefined

});

app.get('/db1',function(req,res)
{
connection.config.database="task" //here  i updating db name before query
connection.query('SELECT * FROM tasks', function (error, results, fields) {
    console.log(results)
    res.json(fields)
connection.end()
})
})

app.get('/db2',function(req,res)
{
connection.config.database="cg_taskview" //db2

connection.query('SELECT * FROM tasks', function (error, results, fields) {
     if (error)
    console.log(error); 
    console.log(results)
    res.json(fields)
     });
connection.end()

})

var server = http.createServer(app);
server.listen(port, function () { 
})

Below is my code for the testing:

var sql = require('mssql/msnodesqlv8');

const config = {server:'localhost', database:'TestDB', 
        options: { trustedConnection: true }};
const config2 = {server:'SomewhereNotExist', database:'TestDB', 
        options: { trustedConnection: true }};

(async () => {
  try { 
    let pool = await sql.connect(config);
    let result = await pool.request().query('select count(1) as cnt from AlarmWithLastStatus');
    console.log('DB1 result:');
    console.dir(result.recordset);

    let pool2 = await sql.connect(config2);
    let result2 = await pool2.request().query('select count(1) as cnt from AlarmWithLastStatus');
    console.log('DB2 result:');
    console.dir(result2.recordset);
  } catch (err) {
    if (err) console.log(err);
  }
}) ();

The output: DB1 result: [ { cnt: 12 } ] DB2 result: [ { cnt: 12 } ]

You could see that the two connection actually points to the same server. If you change the second query to a table that does not exist in this server, that will generate the error you got.

I started experiencing a similar problem when a second MSSQL server was added as a data source to the project ... Fortunately, I found a solution in the examples for tediousjs . Just use the ConnectionPool and don't forget to close the connection:

const settings  = require('./config');
const sql = require('mssql');

exports.someSqlQuery = async function(sqlQuery) {
  const cPool = new sql.ConnectionPool(config);
  cPool.on('error', err => console.log('---> SQL Error: ', err));

  try {
    await cPool.connect();
    let result = await cPool.request().query(sqlQuery);
    return {data: result};
  } catch (err) { 
    return {error: err};
  } finally {
    cPool.close(); // <-- closing connection in the end it's a key
  }
};

If all of yours connections will have a close you can use the connections to different databases on different servers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM