Node.js 操作 PostgreSQL 数据库

这篇node.js操作postgresql数据库,采用的是两个文件的方式实现,一个文件相当于客户端,实现连接数据库,调用相应的函数,而另一个文件是具体实现函数的。

在你安装了node.js,postgresql数据库(不一定是本机)和相应的模块的基础上,在数据库中建表teacher。并插入几条测试数据,这儿插入的测试数据为:

create table teacher(id varchar(10),name varchar(20),pwd varchar(10));

insert into teacher values('1','aaa','111');
insert into teacher values('2','bbb','222');
insert into teacher values('3','ccc','333');
insert into teacher values('4','ddd','444');

1) client.js

var f = require('./function');
var pg = require('pg');

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

var client = new pg.Client(conString);

var value = ['10','fillp','abc'];
insertSQLString = 'insert into teacher values($1,$2,$3)';
selectSQLString = 'select * from teacher';
updateSQLString = "update teacher set NAME='ipone' where ID='4'";
deleteSQLString = "delete from teacher where ID='10'";

client.connect(function(error, results) {
    if(error){
        console.log('ClientConnectionReady Error: ' + error.message);
        client.end();
        return;
    }
    console.log('Connecting to postgres...');
    console.log('Connected to postgres automatically.');
    console.log('connection success...\n');

    f._select(client,selectSQLString);
    f._insert(client,insertSQLString,value);
    f._select(client,selectSQLString);
    f._delete(client,deleteSQLString);
});

相关推荐