以下是上一条回答的 Markdown 格式版本:
npm 安装 SQL Server 相关库指南
在 Node.js 生态里,连接 Microsoft SQL Server 不是装一个叫 "sqlserver" 的包,而是装 TDS 协议客户端。最常用的是 mssql(上层封装,默认底层用 tedious),按需再补驱动。
最常用:装 mssql(推荐大多数项目)
npm install mssql
- 纯 JS、跨平台(Win/Linux/macOS)
- 内置连接池、async/await、参数化查询
- 底层默认走
tedious,不用单独装 tedious,mssql 会自己带
最小可用示例
const sql = require('mssql')
const config = {
user: 'sa',
password: 'yourPwd',
server: 'localhost', // 命名实例写 'localhost\\SQLEXPRESS'
database: 'testdb',
port: 1433,
options: {
encrypt: false, // 本地/内网一般 false;Azure 必须 true
trustServerCertificate: true // 自签证书本地开发可开
}
}
;(async () => {
await sql.connect(config)
const res = await sql.query`SELECT GETDATE() AS now`
console.log(res.recordset)
await sql.close()
})()
只要底层驱动:tedious
npm install tedious
- 更底层、更轻,mssql 和 Sequelize 的 MSSQL dialect 都靠它
- 不适合直接写业务,一般被别的库依赖
用 ORM(Sequelize)
npm install sequelize tedious
sequelize本身不含驱动,MSSQL 场景必须配tedious- 配置
dialect: 'mssql'即可
Windows 集成认证 / 原生 ODBC 驱动
npm install mssql msnodesqlv8
msnodesqlv8走 Microsoft 原生 ODBC 驱动,支持 Windows 身份验证(trustedConnection: true)- 非 Windows 上用 Windows 认证要额外配 Kerberos + ODBC Driver 17/18
- 用之前主机得装 Microsoft ODBC Driver 17 或 18
几个安装后常见的坑
- 本地连不上:SQL Server 要开 TCP/IP(默认端口 1433),Azure 要把
encrypt设true - 自签证书报错:本地开发加
trustServerCertificate: true - Linux 装 msnodesqlv8 失败:缺 ODBC 驱动,先装
msodbcsql18再 npm install - 内网代理装 mssql 失败:可锁版本如
mssql@6.3.2试试
如果你愿意,告诉我你是「本地 SQL Server / Azure SQL / 要 Windows 登录 / 用 TS + NestJS」哪一种场景,我可以直接给你对应的
npm install组合和连接配置。
浙公网安备 33010602011771号