如何使用mssql模块从Node.JS使用Windows身份验证连接到SQL Server

时间:2015-11-14 15:10:02

标签: sql-server node.js npm

您好我无法连接到在节点js中使用Windows身份验证的SQL服务器。我正在使用mssql模块。错误消息是:

[ConnectionError: Login failed for user ''. The user is not associated with a trusted SQL Server connection.]
name: 'ConnectionError',
message: 'Login failed for user \'\'. The user is not associated with a trusted SQL Server connection.',
code: 'ELOGIN' }

这是我的代码:

config = {
    server : "localhost\\MSSQLSERVER",
    database : "mydatabase",
    port : 1433
}

function loadDepts() {
    var conn = new sql.Connection(config);
    var request = sql.Request(conn);

    conn.connect(function(err) {
    if (err) {
        console.log(err);
        return;
    }

    request.query("select deptid, deptname from departments", function(err, table) {
        if (err) {
           console.log(err);
           return;
        }
        else {
           console.log(table);
        }

        conn.close();
        });
    });
}

loadDepts();

12 个答案:

答案 0 :(得分:24)

由于这是一个相当明显的答案,我想添加一个代码片段,该代码片段适用于Trusted Connection。从getglad's编辑的答案中得到了它。

const sql = require("mssql");
require("msnodesqlv8");
const conn = new sql.Connection({
  database: "db_name",
  server: "server_name",
  driver: "msnodesqlv8",
  options: {
    trustedConnection: true
  }
});
conn.connect().then(() => {
  // ... sproc call, error catching, etc
  // example: https://github.com/patriksimek/node-mssql#request
});

使用可信连接,我能够毫无困难地执行存储过程,记录输出和关闭连接,msnodesqlv8已经比其他任何驱动程序更新了(最新版本是2016年10月)截至2016年3月3日),所以这似乎也是一个安全的选择。

以下是使用mssql@4.0.4的示例。唯一的变化是初始需求,它从mssql中引入msnodesqlv8,而sql.Connection现在是sql.ConnectionPool。您还需要更改存储过程调用,因为响应不同,请注明here。感谢Jon的答案,因为他在我做之前更新了我的答案!

const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
  database: "db_name",
  server: "server_name",
  driver: "msnodesqlv8",
  options: {
    trustedConnection: true
  }
});
conn.connect().then(() => {
  // ... sproc call, error catching, etc
  // example: https://github.com/patriksimek/node-mssql#request
});

答案 1 :(得分:20)

我从来没有能够让mssql + windows auth为我的任何项目工作。试试edgeedge-sql - 它对我有用。 Be sure you install all the required packages

https://github.com/tjanczuk/edge

https://github.com/tjanczuk/edge-sql

从那里开始,它非常流畅。

var edge = require('edge');
var params = {
  connectionString: "Server=YourServer;Database=YourDB;Integrated Security=True",
  source: "SELECT TOP 20 * FROM SampleData"
};  
var getData = edge.func( 'sql', params);

getData(null, function (error, result) {
   if (error) { console.log(error); return; }
   if (result) {
    console.log(result);
   }
   else {
    console.log("No results");
   }
 });

修改

嗯...在我的原始回答后10天,显然mssql将Windows Auth添加到包中。他们听到了我们的哭声:) See here。我还没有测试过它,但它正在我的积压测试集成中。我会报告回来。

FWTW,如果mssql符合您的需求,我会顺其自然,因为1)edge-sql已经休眠了2年2)主要撰稿人说他已经离开了这样的项目“ in the caring hands of Microsoft“,因为他不再在那里工作。

编辑2

这不断得到提升,并且有评论说其他一些答案的代码示例要么无效,要么无法在Windows上运行。

这是使用mssql的代码,在Windows上工作,同时安装了msnodesqlv8

var sql = require('mssql/msnodesqlv8');
var config = {
  driver: 'msnodesqlv8',
  connectionString: 'Driver={SQL Server Native Client XX.0};Server={SERVER\\NAME};Database={dbName};Trusted_Connection={yes};',
};

sql.connect(config)
.then(function() {
 ...profit...
})
.catch(function(err) {
  // ... connect error checks
});

答案 2 :(得分:14)

我一直在努力研究如何使用mssql + Windows Auth,这是我如何使用它来处理我的项目。

正如mssql documentation所指出,你也需要安装msnodesqlv8。

npm install msnodesqlv8

现在,关注Aaron Ballard's answer,您可以像这样使用它:

const sql = require('mssql/msnodesqlv8')

const pool = new sql.ConnectionPool({
  database: 'database',
  server: 'server',
  driver: 'msnodesqlv8',
  options: {
    trustedConnection: true
  }
})

pool.connect().then(() => {
  //simple query
  pool.request().query('select 1 as number', (err, result) => {
        console.dir(result)
    })
})

作为一个说明,我试图将此作为对Aaron答案的评论,因为我只是对他的补充/更新,但我没有足够的声誉这样做。

答案 3 :(得分:4)

我尝试了很多变化,这是我的完整解决方案 我正在使用 SQL server Express 我首先将其连接到 MASTER 数据库 您只需要更改“ YOURINSTANCE \\ SQLEXPRESS ” (务必保持上面的双斜线!!!)
我也在使用 INTEGRATED SECURITY 查询完全依赖于任何内容(在您的数据库中) 您需要添加节点包
 ==> NPM INSTALL MSSQL
 ==> NPM INSTALL msnodesqlv8
希望您的连接问题将成为过去 也许吧。
请。

// More here -> https://www.npmjs.com/package/mssql
var sql = require('mssql/msnodesqlv8');
var config = {
  connectionString: 'Driver=SQL Server;Server=YOURINSTANCE\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
  new sql.Request().query('SELECT 1 AS justAnumber', (err, result) => {
    console.log(".:The Good Place:.");
    if(err) { // SQL error, but connection OK.
      console.log("  Shirtballs: "+ err);
    } else { // All is rosey in your garden.
      console.dir(result);
    };
  });
});
sql.on('error', err => { // Connection borked.
  console.log(".:The Bad Place:.");
  console.log("  Fork: "+ err);
});

答案 4 :(得分:1)

对我来说

我使用了如下的连接设置

"server":"",
"domain":"", //sepcify domain of your user 
"port": ,
"user":"", // enter username without domain
"password":"",
"database":""

和TS代码

import * as sql from 'mssql';

const pool = await new sql.ConnectionPool(connection).connect();
const result = await pool.request()
            .query(`SELECT count(idpart) part_computed FROM demo.PARTs;`);
pool.close();
return Promise.resolve(result.recordset);

答案 5 :(得分:0)

我只是在配置中添加了域:“ DNAME” ,因此,此配置可帮助我使用Windows身份验证连接到MS SQL。

const config = {
            driver: 'msnodesqlv8',
            domain: "DNAME",
            user: 'username',
            password: 'pass',
            server: '7.6.225.22',
            database: 'DBNAME',
            requestTimeout: 3600000, //an hour
            options: {
                trustedConnection: true
            },
            debug: true,
            parseJSON: true
        };

答案 6 :(得分:0)

我只能使用msnodesqlv8(仅限Windows环境)和连接字符串(而不是配置对象)来使可信连接正常工作。

const sql = require("msnodesqlv8");

const connectionString = function(databaseName) {
    return "Server=.;Database=" + databaseName + ";Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
}

sql.query(connectionString("DatabaseName"), "SELECT * FROM dbo.Table1" , (err, recordset) => {
    if(err) {
        // Do something with the err object.
        return;
    }

    // else
    // Do something with the recordset object.
    return;
});

答案 7 :(得分:0)

下面的代码对我有用……

const sql = require('mssql/msnodesqlv8')
// config for your database
var config = {
    driver: 'msnodesqlv8',
    server: 'serverNAme\\SQLEXPRESS', 
    database: 'Learn' , 
    options: {
        trustedConnection: true
    }
};

答案 8 :(得分:0)

对我有用 需要安装msnodesqlv8和mssql。还有.......:)

    var dbConfig = {
      driver: 'msnodesqlv8',  
      server: "DESKTOP-66LO4I3",
      database: "FutureHealthCareWeb",
      user: "sa",
      password: "pass@123",
      options: {
        trustedConnection: true
    },
    debug: true,
    parseJSON: true
    }; 
    var sql = require('mssql/msnodesqlv8');

      sql.connect(dbConfig, function (err) {
      if (err) { console.log(JSON.stringify(err)+'..............') }
      else {
        console.log('Connected')
      }
    }
    );

答案 9 :(得分:0)

此版本不需要用户名或密码。

要使用Windows身份验证,我安装了mssql和msnodesqlv8。

然后在我的app.js文件中:

const mssql = require('mssql/msnodesqlv8'); 

请注意,如果您使用的是此示例,则它是mssql而不是sql。

var config = {
  database:'YOUR DATABASE NAME',  
  server: 'localhost\\SQLEXPRESS',
  driver: 'msnodesqlv8',
  options: {
    trustedConnection: true,
    enableArithAbort: true
  }
};

您需要在config中更改数据库名称。除此之外,它应该工作。我的例子:

app.get('/', function (req, res) {

        mssql.connect(config, function (err) {
    
            if (err) console.log(err);
            var request = new mssql.Request();
            request.query('select * from dbo.visit', function (err,  result) {
                if(err) console.log(err);
                console.log(result);
            });
    
        });
    
 });

答案 10 :(得分:0)

这对我有用

const sql = require("mssql/msnodesqlv8");

const conn = new sql.ConnectionPool({
    database: "DB name",
    server: "server name",
    driver: "msnodesqlv8",
    options: {
        trustedConnection: true
    }
});
conn.connect().then((err) => {
    if(err) throw err;
    else console.log("connected");
    
    const req = new sql.Request(conn)
    req.query("select * from table", function(error, res){
        console.log(res)
    })
});

答案 11 :(得分:-1)

我努力使用 Windows身份验证模式连接在远程Windows服务器上运行的mssql服务器。然后我发现解决方案就像下面的代码一样使用了。

sql.connect("Data Source=172.25.x.x,1433;User Id=CSLx\\Name;Password=xxxxxx1234;Initial Catalog=giveTHedataabseNamel;Integrated Security=True",function(err){ }