微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node-postgres【pg】

编程之家收集整理的这个编程导航主要介绍了node-postgres【pg】编程之家,现在分享给大家,也给大家做个参考。

node-postgres【pg】 介绍

Postgresql一个面向对象的关系数据库,postgis是一个基于Postgresql的空间数据库插件,主要用于管理地理空间数据。因此在GIS领域,广泛使用Postgresql作为空间数据库。 

在Node.js中有专门的模块可以用来连接Postgresql数据库,首先从npm资源库中获取数据库模块,名为”pg”:

npm install pg

该模块连接数据库有两种方式:

1 使用连接池

var pg = require('pg');var constring = "postgres://username:password@localhost/database";//this initializes a connection pool//it will keep idle connections open for a (configurable) 30 seconds//and set a limit of 20 (also configurable)pg.connect(constring,function(err,client) {if(err) {return console.error('error fetching client from pool',err);}client.query('SELECT $1::int AS number',['1'],result) {//call `done()` to release the client back to the poolpg.end();if(err) {return console.error('error running query',err);}console.log(result.rows[0].number);//output: 1});});其中”username”、”password”替换为对应数据库用户名密码,”localhost”替换为数据库服务器的地址,”database”替换为数据库名字

2 使用客户端实例连接

var pg = require('pg');

var constring = "postgres://username:password@localhost/database";

var client = new pg.Client(constring);

client.connect(function(err) {

if(err) {

return console.error('Could not connect to postgres',err);

}

client.query('SELECT Now() AS "theTime"',result) {

if(err) {

return console.error('error running query',err);

}

console.log(result.rows[0].theTime);

//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)

client.end();

});

});

网站地址:https://node-postgres.com

GitHub:https://github.com/brianc/node-postgres

网站描述:在nodejs中用来连接Postgresql数据库的模块

node-postgres【pg】

官方网站:https://node-postgres.com

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。