以下是使用 Node.js 和 mssql 模块连接到 MSSQL 数据库并发送查询结果的示例代码:

const http = require('http');
const sql = require('mssql');

const config = {
    user: 'your-username',
    password: 'your-password',
    server: 'your-server',
    database: 'your-database'
};

const server = http.createServer((req, res) => {
    // Connect to the database
    sql.connect(config, err => {
        if (err) {
            console.log(err);
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Error connecting to database');
        } else {
            // Create a new request object
            const request = new sql.Request();
            
            // Execute a query and fetch the result
            request.query('SELECT * FROM your-table', (err, result) => {
                if (err) {
                    console.log(err);
                    res.writeHead(500, {'Content-Type': 'text/plain'});
                    res.end('Error executing query');
                } else {
                    // Convert the result to JSON
                    const jsonResult = JSON.stringify(result.recordset);
                    
                    // Send the JSON result to the client
                    res.writeHead(200, {'Content-Type': 'application/json'});
                    res.end(jsonResult);
                }
                
                // Close the database connection
                sql.close();
            });
        }
    });
});

server.listen(3000, () => {
    console.log('Server running on port 3000');
});

在上面的代码中,我们首先创建了一个 HTTP 服务器,然后使用 mssql 模块连接到 MSSQL 数据库。如果连接失败,我们将发送 500 错误响应并退出。否则,我们将创建一个 SQL 请求对象,并执行查询。如果查询失败,我们将发送 500 错误响应并退出。否则,我们将把结果转换为 JSON 字符串,并将其发送到客户端。最后,我们将关闭数据库连接。

Node.js MSSQL 数据库连接及查询结果发送示例

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

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