node.js搭配mssql模块连接SQL Server数据库,简单查询数据库数据
node版本:V16.18.0
mssql版本:V9.0.1
安装
首先安装mssql模块
npm install mssql
项目中导入
// ESM导入方式
import sql from 'mssql'
准备要连接的数据库配置
mssql通过向connect
方法传入一个config对象来链接数据库
const sqlConfig = {
user: "**", //用户名
password: "**", //密码
database: "**", //要连接的数据库的名字
server: "**.**", //要连接的主机
pool: { //连接池的概念
max: 10,
min: 0,
idleTimeoutMillis: 3000,
},
options: {
encrypt: false, //面向azure
trustServerCertificate: false, //信任服务器证书
},
};
连接
connnect()
返回一个Promise
,可以使用await
等待其连接成功。注意await
要在async
修饰的函数内使用,我使用的版本的nodejs也支持在顶级作用域使用。
await sql.connect(sqlConfig)
查询
向query()
方法传入sql语句进行查询,sql语句可以使用模板字符串包起来,便于改变其查询的条件,例如:
try {
const result = await sql.query(`
SELECT IMEI,Remain,CreateTime
FROM SysUpgradeDevice
WHERE IMEI =${imei}
ORDER BY CreateTime
`);
return result.recordset;
} catch (error) {
console.log("imei:" + imei + "\n" + error);
return null;
}
SQL语句入门比较简单,可以学习一些教程:https://www.runoob.com/sql/sql-tutorial.html
关闭
const conn = sql.connect()
conn.close()
或者
sql.close()