【发布时间】:2015-06-10 19:55:32
【问题描述】:
我正在使用节点 js 和 postgresql。我尝试一次插入多个查询。
数组列表:
var keywordsData = [ { name: 'demo', count: 69 }, { name: 'healthy', count: '22' }, { name: 'cooking', count: '12' }, { name: 'food', count: '9' }, { name: 'home', count: '9' }, { name: 'organic', count: '7' }, { name: 'live', count: '6' }, { name: 'openmrs', count: '6' }];
Javascript 代码:
for (var indexs in keywordsData) {
var item = keywordsData[indexs].name;
var count = keywordsData[indexs].count;
var goalId = 10;
console.log("first" + indexs);
if (item.length > 1) {
client.query("insert into real_keywords(reference_id,keyword,keyword_count) values('" + goalId + "','" + item + "','" + count + "')", function(err, result) {
console.log("last" + indexs);
});
}
}
我的输出是这样的:
first0
first1
first2
first3
first4
first5
first6
first7
last7
last7
last7
last7
last7
last7
last7
last7
预期输出:
first0
last0
first1
last1
first2
last2
first3
last3
first4
last4
first5
last5
first6
last6
first7
last7
请任何人提出解决此问题的最佳方法。
【问题讨论】:
-
好的,这有点离题,所以不要添加它作为答案。 @IyadAssaf 关于异步的答案是正确的。但是您应该为您的 SQL 查询检查另外两个位 1) 不确定
indexes的大小是多少,但您可以一次插入所有行。 stackoverflow.com/questions/6889065/… 2) 您应该考虑使用准备好的语句而不是字符串连接。 postgresql.org/docs/9.2/static/sql-prepare.html
标签: javascript node.js postgresql