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

PostgreSQL中如何在LIKE子句的两个百分号间使用命名变量?

解决yesql在LIKE子句中无法识别命名变量的问题

问题原因

yesql的命名参数解析规则默认只会识别独立的:var标记,当变量被包裹在%:var%这种格式里时,解析器无法正确识别这个参数,导致变量替换失败。

可行解决方案

方案1:在参数值中拼接百分号(推荐)

把SQL里的百分号移到参数值里,让:var作为独立参数被识别:

import { Pool } from 'pg'
import { pg as named } from 'yesql'

const db = new Pool({
    host: 'localhost',
    user: 'postgres',
    password: '1',
    database: 'libcourse'
})

// SQL中只保留命名参数
const query = `select * from table where column like :var`
// 参数值里拼接百分号
const result = await db.query(named(query)({var: '%test%'})).rows

方案2:用PostgreSQL字符串连接符拆分百分号和变量

利用PostgreSQL的||字符串连接操作符,把百分号和变量分开写,让:var成为独立参数:

import { Pool } from 'pg'
import { pg as named } from 'yesql'

const db = new Pool({
    host: 'localhost',
    user: 'postgres',
    password: '1',
    database: 'libcourse'
})

// 用||连接百分号和变量
const query = `select * from table where column like '%' || :var || '%'`
const result = await db.query(named(query)({var: 'test'})).rows

这两种方法都能让yesql正确识别命名参数,同时保持SQL的参数化特性,避免SQL注入风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:01:03