有时您希望使用Express js使用Node js连接到SQL Server。注意使用 Windows身份验证
的SQL Server假设我们有数据库:myDatase,实例:。\ SQLEXPRESS,带有架构的表:dbo.Person
先决条件: 1)节点js, 2)expressjs npm包, 3)Microsoft SQL Server, 4)ODBC驱动程序, 5)mssql npm包, 6)msnodesqlv8 npm pakages。
答案 0 :(得分:3)
这是我的表现:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require('mssql/msnodesqlv8');
var config = {
driver: 'msnodesqlv8',
connectionString: 'Driver={SQL Server Native Client 11.0};Server=.\\SQLEXPRESS;Database=myDatabase;Trusted_Connection=yes;',
};
const pool = new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query("Select * From dbo.Person")
}).then(result => {
let rows = result.recordset
res.status(200).json(rows);
sql.close();
}).catch(err => {
res.status(500).send({ message: `${err}`})
sql.close();
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});