You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS使用mssql库创建SQL Server新连接,禁止复用旧连接

解决mssql库禁用连接复用、每次创建新连接的问题

你当前代码复用连接的原因是使用了mssql提供的全局连接池,sql.connect()默认会复用池中的空闲连接。要实现每次创建全新连接,需要放弃全局连接池,手动创建独立的连接实例:

方案一:手动创建单个Connection实例

每次执行查询时,实例化全新的Connection对象,绑定请求并执行,完成后关闭当前连接:

const sql = require('mssql')

async function runQuery(value) {
    let connection;
    try {
        // 每次创建新的独立连接实例
        connection = new sql.Connection({
            server: 'localhost',
            port: 1433,
            database: 'database',
            user: 'username',
            password: 'password',
            encrypt: true
        });
        await connection.connect();
        
        // 绑定当前连接创建请求对象
        const request = new sql.Request(connection);
        const result = await request.query`select * from mytable where id = ${value}`;
        
        return result;
    } catch (err) {
        // 错误处理逻辑
        console.error('查询出错:', err);
        throw err;
    } finally {
        // 关闭当前连接,不影响其他查询的连接
        if (connection) {
            await connection.close();
        }
    }
}

方案二:创建专属小型连接池

如果需要保持连接池的特性但禁用复用,可以每次创建仅容纳单个连接的新连接池,使用后销毁整个池:

const sql = require('mssql')

async function runQuery(value) {
    let pool;
    try {
        // 每次创建新的连接池,配置为仅允许1个连接
        pool = new sql.ConnectionPool({
            server: 'localhost',
            port: 1433,
            database: 'database',
            user: 'username',
            password: 'password',
            encrypt: true,
            pool: {
                max: 1,   // 池内最大连接数
                min: 0,   // 池内最小空闲连接数
                idleTimeoutMillis: 0  // 空闲连接不自动回收(可选)
            }
        });
        await pool.connect();
        
        const result = await pool.query`select * from mytable where id = ${value}`;
        return result;
    } catch (err) {
        console.error('查询出错:', err);
        throw err;
    } finally {
        // 关闭连接池,销毁当前连接
        if (pool) {
            await pool.close();
        }
    }
}

核心说明

两种方案的本质都是避免使用全局共享的连接池,每次执行查询时创建独立的连接资源,确保不会复用之前的连接,同时在finally块中关闭当前资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者user21621617

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:55:05