← 中文资源

简体中文版本

node-postgres(pg)

Node.js PostgreSQL 客户端,提供连接池、参数化查询、事务和类型化结果。

阅读英文原文

概述

pg 是 Node.js 访问 PostgreSQL 的基础客户端,支持连接池、参数化查询和事务,是许多 ORM 的底层驱动。

核心 API

  • new Pool:创建连接池;按数据库连接预算设置 max、connectionTimeoutMillis 和 idleTimeoutMillis。
  • pool.query:执行参数化查询;值单独传入以避免 SQL 注入,绝不拼接用户输入。
  • Transaction with client:为事务借用一个 client;显式提交或回滚,并在 finally 中释放。
  • pool.end:关闭空闲连接并等待借出的 client;在监听器停止接收工作后用于优雅关闭。
const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, from]);
  await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, to]);
  await client.query('COMMIT');
} catch (err) {
  await client.query('ROLLBACK');
  throw err;
} finally {
  client.release();
}

使用注意

事务必须在同一个 client 上执行。连接池耗尽时设置合理超时并快速失败。查询结果要限制大小,避免一次加载百万行。关闭时先停止接流量。

验证方式

用测试数据库验证参数绑定、事务回滚和连接释放;检查注入字符串被当作值处理。