node.js、pg、postgresql 和插入查询(应用程序挂起)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17319395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:54:16  来源:igfitidea点击:

node.js, pg, postgresql and insert queries (app hangs)

node.jsnode-postgres

提问by Darius Kucinskas

I have the following simple node application for data insertion into postgres database:

我有以下用于将数据插入 postgres 数据库的简单节点应用程序:

var pg = require('pg');
var dbUrl = 'tcp://user:psw@localhost:5432/test-db';

pg.connect(dbUrl, function(err, client, done) {
    for (var i = 0; i < 1000; i++) {
        client.query(
            'INSERT into post1 (title, body, created_at) VALUES(, , ) RETURNING id', 
            ['title', 'long... body...', new Date()], 
            function(err, result) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('row inserted with id: ' + result.rows[0].id);
                }

            });
    }
});

After I run node app.js in terminal it inserts 1000 rows into database, then application hangs, and it do not terminates. What I am doing wrong? I have looked into pg module examples but didn't spot that I'm doing any thing differently…

在终端中运行 node app.js 后,它将 1000 行插入数据库,然后应用程序挂起,并且不会终止。我做错了什么?我查看了 pg 模块示例,但没有发现我在做任何不同的事情......

回答by Darius Kucinskas

I missed call to the client.end(); Now application exits properly:

我错过了给 client.end(); 的电话 现在应用程序正确退出:

pg.connect(dbUrl, function(err, client, done) {
    var i = 0, count = 0; 
    for (i = 0; i < 1000; i++) {
        client.query(
            'INSERT into post1 (title, body, created_at) VALUES(, , ) RETURNING id', 
            ['title', 'long... body...', new Date()], 
            function(err, result) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('row inserted with id: ' + result.rows[0].id);
                }

                count++;
                console.log('count = ' + count);
                if (count == 1000) {
                    console.log('Client will end now!!!');
                    client.end();
                }
            });        
    }
});