如何通过Node.js连接到Postgres

时间:2012-02-09 04:37:50

标签: postgresql node.js

我发现自己试图创建一个postgres数据库,所以我安装了postgres并启动了一个initdb /usr/local/pgsql/data的服务器,然后我用postgres -D /usr/local/pgsql/data启动了该实例,现在我该如何通过节点进行交互?例如,connectionstring会是什么,或者我如何能够找出它是什么。

7 个答案:

答案 0 :(得分:302)

以下是我用来将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();
});

更新: - query.on函数现已弃用,因此上述代码无法按预期工作。作为此解决方案,请查看: - query.on is not a function

答案 1 :(得分:28)

一个简单的方法:pg-promise,如果你熟悉的是承诺;)

var pgp = require('pg-promise')(/*options*/);

var cn = {
    host: 'localhost', // server name or IP address;
    port: 5432,
    database: 'myDatabase',
    user: 'myUser',
    password: 'myPassword'
};
// alternative:
// var cn = 'postgres://username:password@host:port/database';

var db = pgp(cn); // database instance;

// select and return user name from id:
db.one('SELECT name FROM users WHERE id = $1', 123)
    .then(user => {
        console.log(user.name); // print user name;
    })
    .catch(error => {
        console.log(error); // print the error;
    });

另请参阅:How to correctly declare your database module

答案 2 :(得分:12)

只是添加一个不同的选项 - 我使用Node-DBI连接到PG,但也因为能够与MySQL和sqlite交谈。 Node-DBI还包括构建select语句的功能,这对于动态执行动态操作非常方便。

快速示例(使用存储在另一个文件中的配置信息):

var DBWrapper = require('node-dbi').DBWrapper;
var config = require('./config');

var dbConnectionConfig = { host:config.db.host, user:config.db.username, password:config.db.password, database:config.db.database };
var dbWrapper = new DBWrapper('pg', dbConnectionConfig);
dbWrapper.connect();
dbWrapper.fetchAll(sql_query, null, function (err, result) {
  if (!err) {
    console.log("Data came back from the DB.");
  } else {
    console.log("DB returned an error: %s", err);
  }

  dbWrapper.close(function (close_err) {
    if (close_err) {
      console.log("Error while disconnecting: %s", close_err);
    }
  });
});

config.js:

var config = {
  db:{
    host:"plop",
    database:"musicbrainz",
    username:"musicbrainz",
    password:"musicbrainz"
  },
}
module.exports = config;

答案 3 :(得分:1)

一个解决方案可以使用pool个客户端,如下所示:

const { Pool } = require('pg');
var config = {
    user: 'foo', 
    database: 'my_db', 
    password: 'secret', 
    host: 'localhost', 
    port: 5432, 
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000
};
const pool = new Pool(config);
pool.on('error', function (err, client) {
    console.error('idle client error', err.message, err.stack);
});
pool.query('SELECT $1::int AS number', ['2'], function(err, res) {
    if(err) {
        return console.error('error running query', err);
    }
    console.log('number:', res.rows[0].number);
});

您可以在this resource上看到更多详情。

答案 4 :(得分:1)

Slonik是Kuberchaun和Vitaly提出的答案的替代方法。

Slonik实现safe connection handling;您创建一个连接池,并为您处理连接打开/处理。

import {
  createPool,
  sql
} from 'slonik';

const pool = createPool('postgres://user:password@host:port/database');

return pool.connect((connection) => {
  // You are now connected to the database.
  return connection.query(sql`SELECT foo()`);
})
  .then(() => {
    // You are no longer connected to the database.
  });

“ postgres:// user:password @ host:port / database”是您的连接字符串(更典型地,是一个连接URI或DSN)。

这种方法的好处是您的脚本可确保您永远不会意外离开挂起的连接。

使用Slonik的其他好处包括:

答案 5 :(得分:0)

我们也可以使用postgresql-easy。 它基于node-postgressqlutil构建。 注意: pg_connection.js your_handler.js 位于同一文件夹中。 db.js 位于放置的config文件夹中。

pg_connection.js

const PgConnection = require('postgresql-easy');
const dbConfig = require('./config/db');
const pg = new PgConnection(dbConfig);
module.exports = pg;

./ config / db.js

module.exports =  {
  database: 'your db',
  host: 'your host',
  port: 'your port',
  user: 'your user',
  password: 'your pwd',
}

your_handler.js

  const pg_conctn = require('./pg_connection');

  pg_conctn.getAll('your table')
    .then(res => {
         doResponseHandlingstuff();
      })
    .catch(e => {
         doErrorHandlingStuff()     
      })

答案 6 :(得分:0)

连接字符串

连接字符串是以下形式的字符串:

postgres://[user[:password]@][host][:port][/dbname]

(其中[...]中的部分可以有选择地包含或排除)

有效连接字符串的一些示例包括:

postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost

如果您刚刚在本地计算机上启动了数据库,则连接字符串postgres://localhost通常会起作用,因为它使用默认端口号,用户名和密码。如果数据库是使用特定帐户启动的,则可能会发现您需要使用postgres://pg@localhostpostgres://postgres@localhost

如果这些都不起作用,并且您已经安装了docker,则另一个选择是运行npx @databases/pg-test start。这将在docker容器中启动一个postgres服务器,然后为您打印出连接字符串。 pg-test数据库仅用于测试,因此,如果计算机重新启动,则会丢失所有数据。

连接到node.js

您可以使用@databases/pg连接到数据库并发出查询:

const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');

// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:

// import createPool, {sql} from '@databases/pg';

// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');

// wrap code in an `async` function so we can use `await`
async function run() {

  // we can run sql by tagging it as "sql" and then passing it to db.query
  await db.query(sql`
    CREATE TABLE IF NOT EXISTS beatles (
      name TEXT NOT NULL,
      height INT NOT NULL,
      birthday DATE NOT NULL
    );
  `);

  const beatle = {
    name: 'George',
    height: 70,
    birthday: new Date(1946, 02, 14),
  };

  // If we need to pass values, we can use ${...} and they will
  // be safely & securely escaped for us
  await db.query(sql`
    INSERT INTO beatles (name, height, birthday)
    VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
  `);

  console.log(
    await db.query(sql`SELECT * FROM beatles;`)
  );
}

run().catch(ex => {
  // It's a good idea to always report errors using
  // `console.error` and set the process.exitCode if
  // you're calling an async function at the top level
  console.error(ex);
  process.exitCode = 1;
}).then(() => {
  // For this little demonstration, we'll dispose of the
  // connection pool when we're done, so that the process
  // exists. If you're building a web server/backend API
  // you probably never need to call this.
  return db.dispose();
});

您可以在https://www.atdatabases.org/docs/pg

上找到使用node.js查询Postgres的更完整指南。