【问题标题】:node.js, pg, postgresql and insert queries (app hangs)node.js、pg、postgresql 和插入查询(应用挂起)
【发布时间】:2013-06-23 13:15:22
【问题描述】:

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

            });
    }
});

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

【问题讨论】:

  • 由于您的 for 循环作为同步代码执行,应用程序挂起。当它在循环中迭代时,节点可执行文件无法响应其他请求。此外,client.query 调用是同步的,因此当 for 循环运行该查询时,您将使用所有这些查询猛击数据。

标签: node.js node-postgres


【解决方案1】:

我错过了 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();
                }
            });        
    }
});

【讨论】:

  • 其他方式是使用client.on('drain', client.end.bind(client));
  • 如果 i = 207 的 PG 查询失败怎么办?你怎么处理这个?使用具有多个值的单个插入的最佳方法是什么?也就是说,您让 for 循环构建查询并添加适当的数据转义/检查。
猜你喜欢
  • 1970-01-01
  • 2019-01-10
  • 2016-04-03
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多