我是否需要为nodejs + mysql中的每个api关闭池连接

时间:2017-12-11 18:21:29

标签: mysql node.js

我的问题是在这里我为每个API创建池以从MySQL数据库获取数据,在查询完成后我正在关闭池连接。如果我这样做,是否有任何性能问题。什么是实现这一目标的最佳方式。

请原谅我是否有任何问题,请提前致谢。

firstapi: async (req, resp) => {
        let connection;
        try {
            connection = await mysql.createPool(db);
            let firstquery = "first query goes here";
            const [firstapidata] = await connection.execute(verlaufevortagquery);
            resp.json(firstapidata);
        } catch (error) {
            resp.status(500).json({ message: "Failed to execute query", Error: error });
        }
    },

    secondapi: async (req, resp) => {
        let connection;
        try {
            connection = await mysql.createPool(db);
            let secondquery = "second query goes here";
            const [secondata] = await connection.execute(verlaufevortagquery);
            resp.json(secondata);
        } catch (error) {
            resp.status(500).json({ message: "Failed to execute query", Error: error });
        }
    }

1 个答案:

答案 0 :(得分:0)

相反,你可以保持连接打开,没有理由每次都打开它

let connection;
connection = await mysql.createPool(db);
firstapi: async (req, resp) => {

        try {
            use connection.execute here
        } catch (error) {
            resp.status(500).json({ message: "Failed to execute query", Error: error });
        }
    },

    secondapi: async (req, resp) => {
        try {
            use connection.execute here
        } catch (error) {
            resp.status(500).json({ message: "Failed to execute query", Error: error });
        }
    }