Start
新建项目
执行命令:
1 | npm init |
一路回车,完成node.js初始化。
安装
1 | npm install express |
新建文件
连接并查询
node.js连接Sql Server可以用
使用mssql连接数据库并查询代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | var express = require('express'); var app = express(); const sqlStr = "select * from xxx" app.get('/', function (req, res) {<!-- --> var sql = require("mssql"); // config for your database var config = {<!-- --> user: 'username', // update me password: 'pwd', // update me server: 'localhost', // update me database: 'DATA_BASE', // update me encrypt:false // 不加上这个会报错:connect error }; // connect to your database sql.connect(config, function (err) {<!-- --> if (err) console.log(err); // create Request object var request = new sql.Request(); // query to the database and get the records request.query(sqlStr, function (err, recordset) {<!-- --> if (err) console.log(err) // send records as a response res.send(recordset); }); }); }); var server = app.listen(5152, function () {<!-- --> console.log('Server is running..'); }); |
运行app.js
在命令行输入:
1 | node app.js |
在浏览器运行
1 | localhost:5152/ |

参考文档
mssql
Access SQL Server in Node.js
mssql官方网站
Node.Js学习之连接SQLServer数据库
tedious
Step 3: Connecting to SQL using Node.js - SQL Server | Microsoft Docs
其它
node.js 通过tedious 连接SQL SERVER_touten的博客-CSDN博客
Nodejs创建本地json数据文件