node.js,pg,postgresql和insert查询(app hangs)

Dar*_*kas 5 node.js node-postgres

我有以下简单的节点应用程序将数据插入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($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);
                }

            });
    }
});
Run Code Online (Sandbox Code Playgroud)

在终端中运行节点app.js后,它会在数据库中插入1000行,然后应用程序挂起,并且不会终止.我做错了什么?我已经研究过pg模块的例子,但没有发现我做的事情不同......

Dar*_*kas 14

我错过了对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($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();
                }
            });        
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 其他方法是使用client.on('drain',client.end.bind(client)); (2认同)
  • 如果 PG 查询因 i = 207 失败怎么办?你如何处理这个问题?使用具有多个值的单个插入件是最好的方法吗?也就是说,您让 for 循环构建查询,并添加正确的数据转义/检查。 (2认同)