[英]How to insert data to db2 using node js ( ibm_db)
嗨,谁能举一个例子说明如何在nodejs中使用insert语句。 我可以使用选择查询。 但是对于插入查询,我得到的结果为[]。 没有看到错误,但这些值未添加到原始表中。 我正在使用db2,ibm_db,express,nodejs和angularjs。
不久前,我写了一篇关于在Bluemix上使用DB2和node.js的博客条目 。 它包含INSERT语句的代码。
作为插入的一部分
这是相关的代码段, 完整的上下文在博客中 :
exports.insertIP = function(ibmdb,connString,ipinfo) {
console.log("insertIP called",ipinfo);
ibmdb.open(connString, function(err, conn) {
if (err ) {
res.send("error occurred " + err.message);
}
else {
// prepare the SQL statement
conn.prepare("INSERT INTO IP.VISITORS(vtime,ip,country_code,country,region_code,region,city,zip,latitude,longitude,metro,area) VALUES (current timestamp,?,?,?,?,?,?,?,?,?,?,?)", function(err, stmt) {
if (err) {
//could not prepare for some reason
console.log(err);
return conn.closeSync();
}
//Bind and Execute the statment asynchronously
stmt.execute([ipinfo["ip"],ipinfo["country_code"],ipinfo["country_name"],ipinfo["region_code"],ipinfo["region_name"],ipinfo["city"],ipinfo["zipcode"], ipinfo["latitude"], ipinfo["longitude"],ipinfo["metro_code"],ipinfo["area_code"]], function (err, result) {
console.log(err);
// Close the connection to the database
conn.close(function(){
console.log("Connection Closed");
});
});
});
}
})};
我建议并推荐(作为node-ibm_db的成员之一)遵循node-ibm_db github存储库( https://github.com/ibmdb/node-ibm_db ),我们已经更新了README文档以及执行特定任务的API列表。
对于上述查询,您可以使用“ .prepare(sql,callback)”或“ .prepareSync(sql)” API(根据您的要求Async / sync调用),以下是特定API文档的随附代码段和URL链接。
var ibmdb = require("ibm_db"),
cn ="DATABASE=dbname;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=dbuser;PWD=xxx";
ibmdb.open(cn,function(err,conn){
conn.prepare("insert into hits (col1, col2) VALUES (?, ?)",
function (err, stmt) {
if (err) {
//could not prepare for some reason
console.log(err);
return conn.closeSync();
}
//Bind and Execute the statment asynchronously
stmt.execute(['something', 42], function (err, result) {
if( err ) console.log(err);
else result.closeSync();
//Close the connection
conn.close(function(err){});
});
});
});
API文档(Github URL): https : //github.com/ibmdb/node-ibm_db#-8-preparesql-callback
尝试使用以下命令安装jt400 npm install node-jt400 --save
使用以下代码将数据插入表名称foo。 有关详细信息,请访问链接https://www.npmjs.com/package/node-jt400
pool
.insertAndGetId('INSERT INTO foo (bar, baz) VALUES(?,?)',[2,'b'])
.then(id => {
console.log('Inserted new row with id ' + id);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.