我创建了这样的代码,用于从另一个网站的 xml 导出中获取新闻,并且我正在尝试用它填充我的数据库。

function UpdateLunchTime() {
    var httpRequest = require('request');
    var xml2js = require('xml2js');
    var parser = new xml2js.Parser();
    var url = 'http://www...com/export/xml/actualities';
    httpRequest.get({
            url: url
    }, function(err, response, body) {
        if (err) {
            console.warn(statusCodes.INTERNAL_SERVER_ERROR, 
                'Some problem.');
        } else if (response.statusCode !== 200) {
            console.warn(statusCodes.BAD_REQUEST, 
                'Another problem');
        } else {
            //console.log(body);
            parser.parseString(body, function (err2, result) {
                //console.log(result.Root.event);
                var count = 0;
                for (var i=0;i<result.Root.event.length;i++)
                { 
                    //console.log(result.Root.event[i]);
                    InsertActionToDatabase(result.Root.event[i]);
                }
                /*
                result.Root.event.forEach(function(entry) {
                    InsertActionToDatabase(entry);
                });
                */
            });
        }
    });
}

function InsertActionToDatabase(action)
{
    var queryString = "INSERT INTO Action (title, description, ...) VALUES (?, ?, ...)";
    mssql.query(queryString, [action.akce[0], action.description[0],...], {
    success: function(insertResults) {
    },
      error: function(err) {
      console.log("Problem: " + err);
      }
    });
}

对于个人实际情况,它工作正常,但是当我在整个 xml 上运行它时,我收到此错误:

Error: [Microsoft][SQL Server Native Client 10.0][SQL Server]Resource ID : 1. The request limit for the database is 180 and has been reached. See 'http://go.microsoft.com/fwlink/?LinkId=267637' for assistance.

对于最后几个对象,我收到此错误:

Error: [Microsoft][SQL Server Native Client 10.0]TCP Provider: Only one usage of each socket address (protocol/network address/port) is normally permitted.

感谢帮助

有帮助吗?

解决方案

问题是您试图在数据库中进行太多并发(插入)操作。请记住,在 Node.js 中(几乎)一切都是异步的,因此当您调用 InsertActionToDatabase 对于其中一项,此操作将立即开始,而不是等待其完成返回。因此,您基本上是在尝试一次插入所有事件,并且正如错误消息所说,可以与 SQL 服务器建立的并发连接数有限制。

您需要做的是将循环更改为异步运行,方法是等待其中一个操作完成,然后再开始下一个操作(您也可以“批量”一次发送较少数量的操作,在每批完成后继续,但代码稍微复杂一点)如下所示。

var count = result.Root.event.length;
var insertAction = function(index) {
    if (index >= count) return;
    InsertActionToDatabase(result.Root.event[i], function() {
        insertAction(index + 1);
    });
}
insertAction(0);

还有 InsertActionToDatabase 函数将在完成后调用回调参数。

function InsertActionToDatabase(item, done) {
    var table = tables.getTable('event');
    table.insert(item, {
        success: function() {
            console.log('Inserted event: ', item);
            done();
        }
    });
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top