2016-12-16 42 views
0

您好任何人都可以舉例說明如何在nodejs中使用insert語句。我能夠使用選擇查詢。但對於插入查詢,我得到的結果爲[]。沒有錯誤可以看到,但值不會被添加到原始表。我正在使用db2,ibm_db,express,nodejs和angularjs。如何使用節點js將數據插入到db2(ibm_db)

回答

1

前段時間我寫了一個blog entry on using DB2 and node.js on Bluemix。它包含一個INSERT語句的代碼。

作爲插入件的一部分

  1. 首先準備語句,
  2. 然後結合到被插入的值和
  3. 最後執行該語句。

下面是相關代碼片段中,full context is in the blog

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"); 
        }); 
        }); 
       }); 
       } 
      })}; 
1

我建議,並建議(如節點IBM_DB的成員之一)跟隨節點IBM_DB的github倉庫(https://github.com/ibmdb/node-ibm_db) ,我們已經更新了README文檔以及執行特定任務的API列表。

對於上述查詢,您可以使用「.prepare(sql,callback)」或「.prepareSync(sql)」API(根據您的要求進行異步/同步調用),下面是附加的代碼片段和URL鏈接特定的API文檔。

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的網址):https://github.com/ibmdb/node-ibm_db#-8-preparesql-callback

+0

羅希特感謝您的幫助。通過你提到的鏈接和其他幾個鏈接幫助我 –

相關問題