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

SQLite LIKE语句中正确绑定变量的方法咨询

SQLite中LIKE查询绑定变量的正确方式

你的问题出在把占位符?放在了字符串常量的%中间,SQLite会把'%?%'当作完整的字符串字面量,不会解析其中的?作为变量占位符,自然无法正确替换变量,导致查询失败。

下面是两种正确的写法:

方法1:在变量两端拼接通配符%

先给要搜索的字符串加上%前缀和后缀,再传入占位符:

const searchKeyword = 'TheSubStringIWantToSearch';
const sql = `SELECT * FROM NonMandatoryObject 
 JOIN Object ON Object.M_id = NonMandatoryObject.NM_id 
JOIN Pictures ON Pictures.PICS_id = NonMandatoryObject.NM_id 
WHERE description LIKE ?`;

const params = [`%${searchKeyword}%`];

db.all(sql, params, (err, rows) => {
    if (err) console.log('failure');
    else {
        res.send(rows);
        console.log('success');
    }
});

方法2:用SQLite的字符串连接运算符||

在SQL语句里用||把%和占位符拼接起来,变量保持原始值传入:

const searchKeyword = 'TheSubStringIWantToSearch';
const sql = `SELECT * FROM NonMandatoryObject 
 JOIN Object ON Object.M_id = NonMandatoryObject.NM_id 
JOIN Pictures ON Pictures.PICS_id = NonMandatoryObject.NM_id 
WHERE description LIKE '%' || ? || '%'`;

const params = [searchKeyword];

db.all(sql, params, (err, rows) => {
    if (err) console.log('failure');
    else {
        res.send(rows);
        console.log('success');
    }
});

这两种写法都能让SQLite正确识别占位符并替换变量,同时避免SQL注入风险,符合程序规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:35:26