【问题标题】:How can I use a variable as the table name in node-pg? [duplicate]如何在 node-pg 中使用变量作为表名? [复制]
【发布时间】:2020-11-27 06:33:35
【问题描述】:

例如我有这样的查询:

      const rows = await db.query(
        "SELECT * FROM $1 WHERE email = $2 AND password = $3",
        [tableName, email, password]
      );

它给了我一个语法错误。

【问题讨论】:

    标签: postgresql node-postgres


    【解决方案1】:

    这是不可能的,参数化查询仅适用于值(而不是文字),但不适用于 identifiers。您将需要构建 SQL 字符串:

    const rows = await db.query(
      `SELECT * FROM ${db.escapeIdentifier(tableName)} WHERE email = $1 AND password = $2`,
      [email, password]
    );
    

    (假设dbis a PgClient

    如果您事先知道tableName 变量的可能值,您可能会逃脱而无需转义;如果你不这样做,你最好也明确指定架构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2016-06-04
      • 1970-01-01
      相关资源
      最近更新 更多