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

使用TypeORM与MySQL的createQueryBuilder时遇连接已关闭错误求助

问题与解决方案

问题详情

开发基于TypeORM和MySQL的Node.js项目时,使用createQueryBuilder执行查询时触发错误:

Error: Can't add new command when connection is in closed state

涉及代码:

async function connect() {
    await createConnection({
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: 'test',
        password: 'test',
        database: 'testdb',
        entities: [__dirname + '/entity/*.ts'],
        synchronize: true,
    });
}

async function getData() {
    const connection = await connect();
    const repository = connection.getRepository(SomeEntity);

    const data = await repository.createQueryBuilder('entity')
        .where('entity.property = :value', { value: 'someValue' })
        .getMany();

    console.log(data);
}

getData().catch(console.error);

其他不依赖createQueryBuilder的查询方法运行正常,已确认MySQL服务正常、连接参数正确,错误发生在查询执行阶段。

环境信息:

  • TypeORM:0.3.20
  • MySQL:8.0.37
  • mysql2:3.10.2

解决方法

方法1:修复连接函数的返回值

问题核心是connect函数没有返回创建的连接实例,导致getData中connection变量为undefined,后续基于该变量的操作触发连接状态异常。修改connect函数,返回createConnection的执行结果:

async function connect() {
    // 返回创建的连接实例
    return await createConnection({
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: 'test',
        password: 'test',
        database: 'testdb',
        entities: [__dirname + '/entity/*.ts'],
        synchronize: true,
    });
}

方法2:改用TypeORM 0.3.x推荐的DataSource API

TypeORM 0.3.x已将DataSource作为核心API,createConnection属于兼容旧代码的封装,改用DataSource能避免潜在的连接管理问题:

import { DataSource } from "typeorm";

// 定义数据源
const AppDataSource = new DataSource({
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: 'test',
    password: 'test',
    database: 'testdb',
    entities: [__dirname + '/entity/*.ts'],
    synchronize: true,
});

async function getData() {
    // 确保数据源完成初始化
    await AppDataSource.initialize();
    const repository = AppDataSource.getRepository(SomeEntity);

    const data = await repository.createQueryBuilder('entity')
        .where('entity.property = :value', { value: 'someValue' })
        .getMany();

    console.log(data);
    // 可选:使用完毕后关闭数据源
    await AppDataSource.destroy();
}

getData().catch(console.error);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 21:50:13