2016-12-16 3 views
0

Привет Может ли кто-нибудь привести пример использования инструкции insert в nodejs. Я могу использовать select query. Но для запроса insert я получаю результат как []. ошибка не видна, но значения не добавляются в исходную таблицу. Я использую db2, ibm_db, express, nodejs и angularjs.Как вставить данные в db2 с помощью узла js (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 для выполнения конкретных задач.

Для вашего вышеуказанного запроса вы можете использовать API .prepare (sql, callback) "или" .prepareSync (sql) "(согласно вашим требованиям Async/sync call), ниже приведен фрагмент кода и 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 документация (URL Github): https://github.com/ibmdb/node-ibm_db#-8-preparesql-callback

+0

Спасибо Рохит за вашу помощь. Пройдя ссылку, которую вы упомянули, и несколько других ссылок помогли мне –

Смежные вопросы