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

依然范特西╮ 提交于 2019-12-03 13:48:00

问题


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

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($1, $2, $3) 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…


回答1:


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

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($1, $2, $3) 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();
                }
            });        
    }
});


来源:https://stackoverflow.com/questions/17319395/node-js-pg-postgresql-and-insert-queries-app-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!