3

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!

3 Answers 3

1

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 () { 
})
Sign up to request clarification or add additional context in comments.

2 Comments

You are making the queries in the same server! I need to make queries on different servers at the same time. I need to maintain the connections open!
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server. npmjs.com/package/mysql
1

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.

Comments

0

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.

2 Comments

Welcome to SO! That is a comment rather than an answer. Please, edit it to become a reply or wait to win some Rep for commenting. Some people will downvote you reply.
When i try the above code, I am able to connect to the first server without any issues . But when i try connecting to the second server I get Global connection already exists. Let me know if i need to do change something for connecting to more than one sql server from node js.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.