我可以向表中插入一条记录,但我想一次向表中插入多条记录-
我的代码如下-
var doinsert_autocommit = function (conn, cb) {
var query="INSERT INTO test VALUES (:id,:name)";
var values=[{1,'rate'},{5,'ratee'}];
如果我使用 [1,'rat']- 它适用于 插入一行。
conn.execute(
"INSERT INTO test VALUES (:id,:name)",
values, // Bind values
{ autoCommit: true}, // Override the default non-autocommit behavior
function(err, result)
{
if (err) {
return cb(err, conn);
} else {
console.log("Rows inserted: " + result.rowsAffected); // 1
return cb(null, conn);
}
});
};
最佳答案
2019/04/25 更新:
从 2.2 版开始,该驱动程序内置了对批处理 SQL 执行的支持。尽可能使用 connection.executeMany()
。它以较低的复杂性提供了所有性能优势。有关详细信息,请参阅文档的批处理语句执行部分:https://oracle.github.io/node-oracledb/doc/api.html#batchexecution
上一个答案:
目前,该驱动程序仅支持使用 PL/SQL 进行数组绑定(bind),不支持直接 SQL。我们希望在未来改进这一点。现在,您可以执行以下操作...
给定这张表:
create table things (
id number not null,
name varchar2(50) not null
)
/
以下应该有效:
var oracledb = require('oracledb');
var config = require('./dbconfig');
var things = [];
var idx;
function getThings(count) {
var things = [];
for (idx = 0; idx < count; idx += 1) {
things[idx] = {
id: idx,
name: "Thing number " + idx
};
}
return things;
}
// Imagine the 'things' were fetched via a REST call or from a file.
// We end up with an array of things we want to insert.
things = getThings(500);
oracledb.getConnection(config, function(err, conn) {
var ids = [];
var names = [];
var start = Date.now();
if (err) {throw err;}
for (idx = 0; idx < things.length; idx += 1) {
ids.push(things[idx].id);
names.push(things[idx].name);
}
conn.execute(
` declare
type number_aat is table of number
index by pls_integer;
type varchar2_aat is table of varchar2(50)
index by pls_integer;
l_ids number_aat := :ids;
l_names varchar2_aat := :names;
begin
forall x in l_ids.first .. l_ids.last
insert into things (id, name) values (l_ids(x), l_names(x));
end;`,
{
ids: {
type: oracledb.NUMBER,
dir: oracledb.BIND_IN,
val: ids
},
names: {
type: oracledb.STRING,
dir: oracledb.BIND_IN,
val: names
}
},
{
autoCommit: true
},
function(err) {
if (err) {console.log(err); return;}
console.log('Success. Inserted ' + things.length + ' rows in ' + (Date.now() - start) + ' ms.');
}
);
});
这将通过单次往返数据库插入 500 行。此外,数据库中 SQL 和 PL/SQL 引擎之间的单个上下文切换。
如您所见,数组必须单独绑定(bind)(不能绑定(bind)对象数组)。这就是为什么该示例演示如何将它们分解为单独的数组以进行绑定(bind)的原因。随着时间的推移,这一切都应该变得更加优雅,但现在是可行的。
关于node.js - 如何使用 Node.js 将多条记录插入 Oracle DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569126/