加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 如何通过Node.js连接到Postgres

发布时间:2020-12-13 16:53:35 所属栏目:百科 来源:网络整理
导读:我发现自己试图创建一个postgres数据库,所以我安装postgres和启动一个服务器与initdb /usr/local/pgsql / data,然后我启动该实例postgres -D /usr/local/pgsql / data现在如何通过节点与此交互?例如,什么是connectionstring,或我怎么能找到它是什么。
我发现自己试图创建一个postgres数据库,所以我安装postgres和启动一个服务器与initdb /usr/local/pgsql / data,然后我启动该实例postgres -D /usr/local/pgsql / data现在如何通过节点与此交互?例如,什么是connectionstring,或我怎么能找到它是什么。
这里是一个例子,我用来连接node.js到我的Postgres数据库。

我使用的node.js中的接口可以在这里找到https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

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

//queries are queued and executed one after another once the connection becomes available
var x = 1000;

while (x > 0) {
    client.query("INSERT INTO junk(name,a_number) values('Ted',12)");
    client.query("INSERT INTO junk(name,a_number) values($1,$2)",['John',x]);
    x = x - 1;
}

var query = client.query("SELECT * FROM junk");
//fired after last row is emitted

query.on('row',function(row) {
    console.log(row);
});

query.on('end',function() {
    client.end();
});



//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text,(optional) parameter values,and (optional) query name
client.query({
    name: 'insert beatle',text: "INSERT INTO beatles(name,height,birthday) values($1,$2,$3)",values: ['George',70,new Date(1946,02,14)]
});

//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
    name: 'insert beatle',values: ['Paul',63,new Date(1945,04,03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1",['john']);

//can stream row results back 1 at a time
query.on('row',function(row) {
    console.log(row);
    console.log("Beatle name: %s",row.name); //Beatle name: John
    console.log("Beatle birth year: %d",row.birthday.getYear()); //dates are returned as javascript dates
    console.log("Beatle height: %d' %d"",Math.floor(row.height / 12),row.height % 12); //integers are returned as javascript ints
});

//fired after last row is emitted
query.on('end',function() {
    client.end();
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读