时间:2021-07-01 10:21:17 帮助过:98人阅读
这篇node.js操作postgresql数据库,采用的是两个文件的方式实现,一个文件相当于客户端,实现连接数据库,调用相应的函数,而另一
上一篇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 where";
deleteSQLString = "delete from teacher where";
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);
});