Подтвердить что ты не робот

Как подключиться к Postgres через Node.js

Я пытаюсь создать базу данных postgres, поэтому я установил postgres и запустил сервер с initdb /usr/local/pgsql/data, затем я начал этот экземпляр с postgres -D /usr/local/pgsql/data теперь, как я могу взаимодействовать с этим через node? Например, что бы было connectionstring, или как я могу узнать, что это такое.

4b9b3361

Ответ 1

Вот пример, который я использовал для подключения node.js к моей базе данных Postgres.

Интерфейс в файле node.js, который я использовал, можно найти здесь https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:[email protected]: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 не является функцией

Ответ 2

Современный и простой подход: pg-обещание:

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

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

// alternative:
// var cn = 'postgres://username:[email protected]:port/database';

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

// select and return a single 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;
    });

// alternative - new ES7 syntax with 'await':
// await db.one('SELECT name FROM users WHERE id = $1', [123]);

См. также: Как правильно объявить модуль базы данных.

Ответ 3

Просто добавьте другой вариант - я использую 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;

Ответ 4

Одним из решений может быть использование 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);
});

Вы можете увидеть более подробную информацию о этом ресурсе.

Ответ 5

Слоник - это альтернатива ответам, предложенным Куберчауном и Виталием.

Slonik реализует безопасную обработку соединений; вы создаете пул соединений, и открытие/обработка соединений для вас обрабатывается.

import {
  createPool,
  sql
} from 'slonik';

const pool = createPool('postgres://user:[email protected]: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:[email protected]:port/database - это строка вашего соединения (или более канонически URI или DSN соединения).

Преимущество этого подхода заключается в том, что ваш сценарий гарантирует, что вы никогда не оставите случайно прерванные соединения.

Другие преимущества использования Slonik:

Ответ 6

Мы также можем использовать postgresql-easy. Он построен на node-postgres и sqlutil. Примечание. 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()     
      })