Why the mysql connection is closed unexpectedly in node.js?

25 Views Asked by At

Here is my code:

import { DbConfig } from './DBConfig.js';
import mysql from 'mysql2';
export default class DBO {
    constructor() {
        DbConfig["multipleStatements"] = true;
        DbConfig["insecureAuth"] = true;
        const connection = mysql.createConnection(DbConfig);
        let sqlString;
        
        .....................
        
        this.getOldNetworkReport = async reportPeriod => {
            sqlString = "select * from network_service_pledge_performance where report_period=?";
            try {
                let temp = await executeQuery(sqlString, reportPeriod);
                if (temp.length > 0) {
                    result = { "network_pledge_performance": {} }
                    for (let i=0;i < temp.length;i++){
                        let item=temp[i];
                        result["network_pledge_performance"][item.sub_cat_id] = { 
                            name: item.sub_cat_name, 
                            count: item.count, 
                            down_time: item.down_time 
                        };
                    }
                    sqlString = "select * from network_incident_summary where report_period=?";
                    temp = await executeQuery(sqlString,[reportPeriod]);
                    result["network_incident_summary"] = temp[0];
                }
                return result
            } catch (error) {
                console.log("=============================");
                console.log("Something Wrong when getting old network report Data.");
                console.log(error.stack);
                console.log("=============================");
            }
        }
        this.close = () => {
            connection.end(err => {
                if (err) throw err;
                console.log("Disconnect from " + DbConfig["host"] + " successfully!");
            });
        }
        async function executeQuery(sql, para) {
            try {
                const [rows] = await connection.promise().query(sql, para);
                return rows;
            } catch (err) {
                throw (err);
            }
        }
    }
}   

Here is DBConfig.js:

import dotenv from 'dotenv';
dotenv.config({ path: '.env.' + process.env.NODE_ENV });
export const DbConfig = {
    charset: process.env["DATABASE_CHARSET"],
    host: process.env["DATABASE_HOST"],
    user: process.env["DATABASE_USER_NAME"],
    password: process.env["DATABASE_PASSWORD"],
    port: process.env["DATABASE_PORT"],
    database: process.env["DATABASE_NAME"]
}

Here is the caller code:

let dboObj = new DBO();
        try {
            return dboObj.getOldNetworkReport(startDate);
        } catch (error) {
            console.log("===============================");
            console.log("Something Wrong when getting old network report data:");
            console.log(error.stack);
            console.log("===============================");
        }
        finally {
            dboObj.close();
        };

When I call the dbo.getOldNetworkReport('2023-09-01'), I got the following error:

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

I have tried to swap the sequence of SQL execution, unfortunately, the problem is still existed.

If I execute 1 SQL command (I have tried both of them), it works.

So, I want to know why the connection close unexpectedly.

0

There are 0 best solutions below