如何断开与数据库的连接?每次查询产生新的连接

时间:2019-03-04 04:37:49

标签: javascript node.js postgresql

我对池和与PostgreSQL和节点的连接一无所知。我已经成功创建了一个池,但是每次有一个新查询时,它都会打开一个新连接,而不会关闭它。这是有问题的,因为服务器只能容纳20个连接。要注意的另一件事是,我尝试使用pool.end(),但是即使我将其放在程序的最后一行,它也给我中间中的查询带来了错误说:

  

在池上调用完结束后无法使用池

即使我没有在池结束之后调用它,因为池的结尾是程序的最后一行...因此,我将pool.end()放在查询结束时,即使它只是为了绕过错误是多余的。

基本上,我每次接收到聊天消息时,都会尝试增加“ XP”。

这是我的代码:

bot.on("message", message => {
if (message.author.bot) return;
if (message.channel.type === "dm" ) return;

const parse = require("pg-connection-string");
const { Pool } = require ('pg');    
const pool = new Pool({
    connectionString: process.env.DATABASE_URL.parse,
    port: 5432,

    host: "myhost",
    database: "mydatabase",
    user: "myuser",
   password:   "secret",
    ssl: true,

});

pool.connect(err => {
    if(err) console.log(err);
    console.log('Connected to PostgresSQL');
});
pool.query(`SELECT * FROM xp WHERE id = '${message.author.id}'`, (err, results) => {
    if (err) console.log("err = " + err);

    console.log("results = ", results);
    console.log("Row count = ", results.rowCount);


    if (results.rowCount == 0) {
        console.log("IF: ");

        let authorData = `INSERT INTO xp (id, xp) VALUES ($1, $2)`;
        let authorDataValues = [message.author.id, incrementMessageCount()];


        pool.query(authorData, authorDataValues, err => {   
            if (err) console.log("Failed to insert!  Err = ", err);
            else {
                console.log("Successfully added " + message.author.id + "to the database!");

                // CLOSING THE POOL HERE BUT CONNECTION STAYS OPEN
                pool.end(err => {
                    if (err) console.log('errored');
                    console.log('Not logged to PostgresSql');
                });
            }
        });
        console.log("here: ");
    }
        else {
            console.log("ELSE: ");
            let xp = results.rows[0].xp + incrementMessageCount();
            console.log ("xp = " + xp);
            pool.query(`UPDATE xp SET xp = ${xp} WHERE id = '${message.author.id}'`, err => {
                if (err) console.log("Failed to increment!  Err = ", err);
                else {
                    console.log("Successfully incremented " + message.author.id + " xp table!");

                    // CLOSING THE POOL HERE BUT CONNECTION IS STILL OPEN
                    pool.end(err => {
                        if (err) console.log('errored');
                        console.log('Not logged to PostgresSql');
                    });
                }
            });

        }           
});

});

向聊天室发送10条消息后,它可以正确增加,但是我检查了Heroku仪表板以查看数据库的工作方式,并说20个连接中有12个连接。查询后如何关闭连接?

0 个答案:

没有答案