2016-12-16 60 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

罗希特感谢您的帮助。通过你提到的链接和其他几个链接帮助我 –