node.js訪問postgresql 數據庫


1)安裝pg模塊:
  進入到/usr/local/lib:發現有一個node_schedules目錄,裏面放的是你安裝的模塊
 
  npm install -g node-gyp
  export $PATH=$PATH:/usr/local/pgsql/bin/
  npm install pg              //-g 表示全局

2)連接數據庫並訪問
  連接字符串=“tcp:// 用戶名 : 密碼 @localhost:5432/ 庫名”;

  1) 事件形式:
     var pg = require('pg');
     var MATH = require('math');
     var constring = "tcp://postgres:1234@localhost/my";

     var client = new pg.Client(constring);
     client.connect();

     client.query("create temp table beatle(name varchar(10),height integer)");
     client.query("insert into beatle(name,height) values('john',50)");
     client.query("insert into beatle(name,height) values($1,$2)",['brown',68]);
     var query = client.query("select * from beatle");

     query.on('row',function(row){
    console.log(row);
    console.log("Beatle name:%s",row.name);
    console.log("beatle height:%d' %d\"",MATH.floor(row.height/12),row.height%12);
     });

     query.on('end',function(){
    client.end();
     });
    
     測試成功,輸出內容爲:
      { name: 'john', height: 50 }
      Beatle name:john
      beatle height:4' 2"
      { name: 'brown', height: 68 }
      Beatle name:brown
      beatle height:5' 8"
   
    2)回調函數形式:
      var pg = require('pg');

      var conString = "tcp://postgres:1234@localhost/my";

      var client = new pg.Client(conString);
      client.connect(function(err) {
    client.query('SELECT NOW() AS "theTime"', function(err, result) {
      console.log(result.rows[0].theTime);
          client.end();
    })
      });

     測試成功,輸出結果爲:
      Wed Jan 23 2013 14:30:12 GMT+0800 (CST)
     
    3) 用回調方式實現上面的事件形式:
      var pg = require('pg');
      var MATH = require('math');
      var constring = "tcp://postgres:1234@localhost/my";

      var client = new pg.Client(constring);

      client.connect(function(err){
      client.query("create temp table beatle(name varchar(10),height integer)");
      client.query("insert into beatle(name,height) values('john',50)");
      client.query("insert into beatle(name,height) values($1,$2)",['brown',68]);
      client.query("select * from beatle ",function(err,result){
          console.log(result);
          for(var i=0;i<result.rowCount;i++ )
          {
          console.log(result.rows[i]);
          console.log("Beatle name:%s",result.rows[0].name);
          console.log("beatle height:%d' %d\"",MATH.floor(result.rows[0].height/12),result.rows[0].height%12);
          }
          client.end();
       });
      });
       
      測試成功,輸出結果爲:
      { command: 'SELECT',
    rowCount: 2,
    oid: NaN,
    rows: [ { name: 'john', height: 50 }, { name: 'brown', height: 68 } ] }
      { name: 'john', height: 50 }
      Beatle name:john
      beatle height:4' 2"
      { name: 'brown', height: 68 }
      Beatle name:john

      beatle height:4' 2"


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章