使用Node.js从SQL Server数据库读取数据

本教程将指导你使用Node.js和mssql模块从SQL Server数据库中获取数据。

1. 安装 mssql 模块:

使用npm安装mssql模块:

npm install mssql

2. 代码示例:

以下是使用Node.js从SQL Server表中获取数据的示例代码:

const sql = require('mssql');

// 配置数据库连接
const config = {
    user: 'your_username',
    password: 'your_password',
    server: 'your_server',
    database: 'your_database',
    options: {
        encrypt: true // 如果使用Azure,需要启用加密
    }
};

// 创建连接池
const pool = new sql.ConnectionPool(config);

// 连接池连接
pool.connect().then(() => {
    // 创建请求对象
    const request = new sql.Request(pool);

    // 执行查询
    request.query('SELECT * FROM your_table WHERE id = 1').then(result => {
        console.log(result.recordset[0]); // 输出第一条记录
    }).catch(err => {
        console.error(err);
    });
}).catch(err => {
    console.error(err);
});

3. 代码解释:

  • 首先,我们使用require('mssql')加载mssql模块。
  • 然后,我们配置数据库连接信息,包括用户名、密码、服务器地址、数据库名称等。
  • 接下来,我们使用new sql.ConnectionPool(config)创建一个连接池。
  • 使用pool.connect()连接到数据库。
  • 连接成功后,我们使用new sql.Request(pool)创建一个请求对象。
  • 使用request.query(sql)执行SQL查询,并将查询结果传递给回调函数。
  • 在回调函数中,我们可以通过result.recordset访问查询结果,并使用console.log()输出第一条记录。

4. 注意:

  • 将示例代码中的占位符替换为你的实际数据库连接信息和目标表名。
  • 确保你的SQL Server数据库允许远程连接。
  • 根据你的数据库版本和配置,你可能需要调整连接选项。

希望这篇教程能够帮助你使用Node.js从SQL Server数据库中获取数据。

Node.js从SQL Server数据库读取数据教程

原文地址: https://www.cveoy.top/t/topic/jPoW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录