[英]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.