I’m working on a Node.js project using TypeORM with MySQL. I’ve encountered an issue where I get the following error when trying to execute a query using createQueryBuilder:
Error: Can't add new command when connection is in closed state
<code>
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);
</code>
<code>
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);
</code>
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);
Other methods that don’t use createQueryBuilder work fine.
I’ve made sure that the MySQL server is running and the database connection parameters are correct. The error occurs when the query is executed.
Additional Info:
TypeORM version: 0.3.20
MySQL version: 8.0.37
mysql2 version: 3.10.2