You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pg-promise的动态查询中使用rowMode: array模式

在pg-promise动态查询中使用rowMode: array返回数组数组

要实现动态查询并返回数组形式的行数据,核心是确保位置占位符($1、$2...)和参数数组的顺序严格对应,同时在查询选项中指定rowMode: 'array'。以下是具体实现方案和示例:

核心思路

  1. 动态构建SQL时,用$${序号}生成位置占位符,同时维护一个参数数组,按顺序存入动态值
  2. 执行查询时,通过第三个参数传入{ rowMode: 'array' },强制返回数组的数组而非对象数组

TypeScript代码示例

手动拼接动态查询

import pgp from 'pg-promise';

// 初始化数据库连接
const db = pgp()('postgres://your-user:your-pass@your-host:5432/your-db');

async function getLatestNews(
  category?: string,
  limit = 10,
  offset = 0
): Promise<Array<Array<any>>> {
  let sql = `SELECT id, title, publish_date, content FROM news`;
  const params: any[] = [];
  let paramCount = 1;

  // 动态添加分类筛选条件
  if (category) {
    sql += ` WHERE category = $${paramCount}`;
    params.push(category);
    paramCount++;
  }

  // 添加排序和分页逻辑
  sql += ` ORDER BY publish_date DESC LIMIT $${paramCount} OFFSET $${paramCount + 1}`;
  params.push(limit, offset);

  // 执行查询并指定rowMode
  return db.query(sql, params, { rowMode: 'array' });
}

// 使用示例
getLatestNews('tech', 5, 0)
  .then(rows => {
    // 每一行是 [id, title, publish_date, content] 形式的数组
    console.log('数组形式的新闻数据:', rows);
  })
  .catch(err => console.error('查询失败:', err));

用pg-promise的Helpers安全拼接查询

如果担心手动拼接SQL出错,可以用官方提供的helpers工具类:

import pgp, { helpers } from 'pg-promise';

const db = pgp()('postgres://your-user:your-pass@your-host:5432/your-db');

async function getLatestNewsWithHelpers(
  category?: string,
  limit = 10,
  offset = 0
): Promise<Array<Array<any>>> {
  const conditions: string[] = [];
  const params: any[] = [];

  // 动态构建筛选条件
  if (category) {
    conditions.push(`category = $${params.length + 1}`);
    params.push(category);
  }

  const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';

  // 拼接完整SQL
  const sql = helpers.concat([
    'SELECT id, title, publish_date, content FROM news',
    whereClause,
    `ORDER BY publish_date DESC LIMIT $${params.length + 1} OFFSET $${params.length + 2}`
  ]);

  params.push(limit, offset);

  return db.query(sql, params, { rowMode: 'array' });
}

关键注意事项

  • 占位符的序号($1、$2)必须和参数数组的索引+1严格对应(比如数组第0个元素对应$1)
  • rowMode的取值是字符串'array',不要写错大小写
  • 除了db.query,使用db.any、db.many等方法时,同样可以通过第三个参数传入{ rowMode: 'array' }

内容的提问来源于stack exchange,提问作者PirateApp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 23:42:12