一、下載Node.js postgres驅動
Node.js里面沒有postgres模塊的,我們需要安裝node-postgres模塊。 node-postgres模塊的下載地址為:https://github.com/brianc/node-postgres。下載完成后,解壓到pg目錄,pg里面的文件目錄結構如下圖所示:
二、編寫js代碼
1、在D盤新建文本文件重命名為,test-postgres.js。內容如下:
1 var pg = require('./pg'); //加載模塊node-postgres,該模塊要與本文件放於同一個目錄下 2 var conString = "postgres://postgres:postgres@localhost:5432/node-test";//此時數據庫必須已經創建 3 //anything://user:password@host:port/database 4 var client = new pg.Client(conString); 5 6 client.connect(function(err) { 7 if(err) { 8 return console.error('could not connect to postgres', err); 9 } 10 11 //刪除存在表 12 console.log("Dropping table 'person'") 13 var query = client.query("drop table if exists person"); 14 query.on('end', function() { 15 console.log("Dropped!"); 16 }); 17 18 //創建表 19 console.log("Creating table 'person'"); 20 query = client.query("create table person(id serial, username varchar(10), password varchar(10), age integer)"); 21 query.on('end', function(){ 22 console.log("Created!"); 23 }); 24 25 //添加 26 client.query('INSERT INTO person(username, password, age) VALUES($1, $2, $3)', ["zhangsan", "123456", 20], function(err, result) { 27 console.log( "====================add========================"); 28 if(err) { 29 console.log(err); 30 return rollback(client); 31 } 32 console.log( result); 33 }); 34 35 36 //查詢 37 client.query('select username, password, age from person where id = $1', [3], function(err, result) { 38 console.log( "===================query========================="); 39 if(err) { 40 console.log(err); 41 } 42 console.log(result.rows[0]); 43 }); 44 45 //更新 46 client.query('update person set password=$1 where id = $2', ["11a",1], function(err, result) { 47 console.log( "=====================update======================="); 48 if(err) { 49 console.log(err); 50 } 51 console.log(result); 52 }); 53 54 //刪除 55 client.query('delete from person where id = $1', [1], function(err, result) { 56 console.log( "====================remove======================="); 57 if(err) { 58 console.log(err); 59 } 60 console.log(result); 61 client.end(); 62 }); 63 64 }); 65 66 var rollback = function(client) { 67 client.query('ROLLBACK', function() { 68 client.end(); 69 }); 70 };
2、將pg目錄拷貝至test-postgres.js文件相同目錄下,cmd進入D盤 運行命令 node testmysql.js 回車即可運行。