简体   繁体   English

Node Express 多 SQL 服务器连接

[英]Node Express Multiple SQL server Connection

I need to connect to diferent databases on direfent servers.我需要连接到不同服务器上的不同数据库。 The servers are Microsoft SQL Server.服务器是 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'.错误是无效的对象名称“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.我使用 MySQL 实现你可以通过在创建连接之前传递空数据库参数和字母更新数据库来做同样的事情 mssql。

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 } ]输出: DB1 结果:[ { cnt: 12 } ] DB2 结果: [ { 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 .当第二个 MSSQL 服务器作为数据源添加到项目中时,我开始遇到类似的问题......幸运的是,我在tediousjs的示例中找到了解决方案。 Just use the ConnectionPool and don't forget to close the connection:只需使用 ConnectionPool 并且不要忘记关闭连接:

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.如果您的所有连接都将关闭,您可以使用与不同服务器上不同数据库的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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