Postgresql 如何通过Node.js连接到Postgres

Postgresql 如何通过Node.js连接到Postgres,postgresql,node.js,Postgresql,Node.js,我发现自己正在尝试创建一个postgres数据库,所以我安装了postgres,并用initdb/usr/local/pgsql/data启动了一个服务器,然后用postgres-D/usr/local/pgsql/data启动了该实例,现在我如何通过节点与之交互?例如,connectionstring是什么,或者我如何才能找到它是什么 下面是一个将node.js连接到Postgres数据库的示例 我在node.js中使用的接口可以在这里找到 更新:-现在已弃用query.on函数,因此上述代码

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

下面是一个将node.js连接到Postgres数据库的示例

我在node.js中使用的接口可以在这里找到


更新:-现在已弃用
query.on
函数,因此上述代码将无法正常工作。为了解决这个问题,请看:-

只需添加一个不同的选项-我使用连接到PG,但这也是由于能够与MySQL和sqlite通信。节点DBI还包括构建select语句的功能,这对于动态工作非常方便

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

config.js:

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

一种现代而简单的方法:


另请参见:.

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

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);
});
您可以查看更多详细信息。

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

斯洛尼克工具;您创建了一个连接池,并为您处理连接打开/处理

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的其他好处包括:

    • 我们也可以使用。 它是建立在和之上的。 注意:pg\u connection.js和您的\u 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;
      
      module.exports =  {
        database: 'your db',
        host: 'your host',
        port: 'your port',
        user: 'your user',
        password: 'your pwd',
      }
      
        const pg_conctn = require('./pg_connection');
      
        pg_conctn.getAll('your table')
          .then(res => {
               doResponseHandlingstuff();
            })
          .catch(e => {
               doErrorHandlingStuff()     
            })
      
      /config/db.js

      const PgConnection = require('postgresql-easy');
      const dbConfig = require('./config/db');
      const pg = new PgConnection(dbConfig);
      module.exports = pg;
      
      module.exports =  {
        database: 'your db',
        host: 'your host',
        port: 'your port',
        user: 'your user',
        password: 'your pwd',
      }
      
        const pg_conctn = require('./pg_connection');
      
        pg_conctn.getAll('your table')
          .then(res => {
               doResponseHandlingstuff();
            })
          .catch(e => {
               doErrorHandlingStuff()     
            })
      
      你的_handler.js

      const PgConnection = require('postgresql-easy');
      const dbConfig = require('./config/db');
      const pg = new PgConnection(dbConfig);
      module.exports = pg;
      
      module.exports =  {
        database: 'your db',
        host: 'your host',
        port: 'your port',
        user: 'your user',
        password: 'your pwd',
      }
      
        const pg_conctn = require('./pg_connection');
      
        pg_conctn.getAll('your table')
          .then(res => {
               doResponseHandlingstuff();
            })
          .catch(e => {
               doErrorHandlingStuff()     
            })
      
      连接字符串 连接字符串是以下形式的字符串:

      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@本地主机
      postgres://postgres@本地主机

      如果这些都不起作用,并且您已经安装了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();
      });
      

      您可以在

      上找到关于使用node.js查询Postgres的更完整指南,这正是我喜欢看到的示例类型。清晰且包含足够的代码。谢谢JustBob。您在pg_hba.conf中添加了什么以允许从node.js进行连接?感谢所有0.0.0.0/0 md5。如果我没记错的话,这个条目将允许任何IP连接。请记住,这不是特定于节点的,而是特定于PostgreSQL的。在postgresql.conf中,我还有listen_地址='*'。对于生产设置,请通读文档,以确保您没有在任何地方开孔。我在我的开发设置中使用它,所以我可以允许任何机器连接。列出的构造参数是genius,正是我想要的。非常感谢。仔细的虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面发生变化,只有链接的答案可能会变得无效。在理想的世界中——是的,但是,正如你在上面看到的,这里接受的答案——也只有链接。与此相同,从链接提供的信息中抽象出来太多了,而且考虑到这两个链接都提供给GitHub的公共存储库,它们失效的几率并不比StackOverflow失效的几率大。也许只需提供一个简单的示例,将其用于一些非常基本的事情,这应该只占用几行,但足以使其不只是链接。@Qantas94Heavy,我刚刚做了,在向下投票时暂停:)@vitaly-t:可能有人将该帖子标记为“非常低质量”,如果该帖子在处理标记之前被编辑或删除,将自动向下投票。嘿,Mlacetti,我在尝试连接SQLite3数据库并对其运行测试时遇到了类似的问题。我正在学习一个关于使用DBWrapper的教程,这就是为什么我要联系您。我的问题是:节点DBI早就被放弃了,不再受支持。谢谢,我的缺少
      数据库:
      参数,添加它最终修复了连接。您没有使用“config”。这是一个很好的简明示例。谢谢