PG NPM包未连接到Localhost DB

时间:2016-04-12 12:47:55

标签: javascript node.js postgresql npm

我无法让pg软件包在本地系统上运行。我试图运行以下内容:

var pg = require('pg');
var con_string = "postgres://user:password@localhost:5432/documentation";

var client = new pg.Client();
client.connect(con_string, function(err, res) {
// stuff here
});

但我一直在TypeError: callback is not a function

是否需要更改设置才能通过连接字符串连接到数据库?我在本地计算机上的数据库上尝试了上面user:password中使用的用户名和密码,我可以很好地连接。

我也在我安装node的项目目录中的pg shell中尝试过,但没有运气。

由于

这是我从运行以下答案得到的错误:

$ node pg_test.js 
error fetching client from pool { [error: password authentication failed for user "jake"]

1 个答案:

答案 0 :(得分:0)

直接来自https://github.com/brianc/node-postgres的文档:

var pg = require('pg');
var conString = "postgres://user:password@localhost:5432/documentation";

//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 10 (also configurable)
pg.connect(conString, function(err, client, done) {
  if(err) {
    return console.error('error fetching client from pool', err);
  }
  client.query('SELECT $1::int AS number', ['1'], function(err, result) {
    //call `done()` to release the client back to the pool
    done();

    if(err) {
      return console.error('error running query', err);
    }
    console.log(result.rows[0].number);
    //output: 1
  });
});