以下是使用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字符串,并将其发送到客户端。最后,我们将关闭数据库连接。

nodeJS mssqlconnect respend 发送 result

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

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