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

参数化查询中字符串需转义吗?Express无ORM实现CRUD查询无结果排查

问题描述

正在学习Express,不使用ORM实现简单的CRUD功能。目前遇到的问题是调用Model.findBy()方法无法查询到任何记录,代码如下:

model User {
  static async findBy(payload) {
    try {
      let attr  = Object.keys(payload)[0]
      let value = Object.values(payload)[0]

      let user = await pool.query(
        `SELECT * from users WHERE $1::text = $2::text LIMIT 1;`,
        [attr, value]
      );

      return user.rows; // empty :-(
    } catch (err) {
      throw err
    }
  }
}

User.findBy({ email: 'foo@bar.baz' }).then(console.log);
User.findBy({ name: 'Foo' }).then(console.log);

在psql中执行SQL语句是正常的,只要给$2::text加上单引号即可,示例如下:

SELECT * FROM users WHERE email = 'foo@bar.baz' LIMIT 1;

但这种写法在参数化查询中不支持,也尝试过'($2::text)'以及各类转义写法,都不符合node-postgres官方文档的要求。想知道user.rows返回空的原因是获取attr和value的方式有误?还是传递字符串参数时需要做特殊转义?

问题解答

该问题和字符串转义无关,根源在于动态列名的处理。列名不属于查询参数可赋值的标识符范畴,无法通过查询参数动态设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:18:03