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

Node.js中SQLite更新查询失败:字符串字段报错,数字字段正常

问题解决:SQLite字符串字段更新报错

错误原因

你直接将字符串变量拼接到SQL语句中,未给字符串值添加单引号,导致SQL引擎把hamed识别为列名而非字符串内容,因此触发SQLITE_ERROR: no such column: hamed错误。数字类型不需要引号包裹,所以数字字段更新无异常。

解决方案

方案1:手动添加单引号(不推荐,存在SQL注入风险)

修改SQL语句,给字符串字段值加上单引号:

const query = `update controls set controlCode=${controlsCode} , controlName='${controlsName}' where id =${id}`;

注意:如果字符串中包含单引号(比如O'Neil),这种方式会直接报错,且容易被SQL注入攻击,仅临时测试可用。

方案2:使用Sequelize参数化查询(推荐,安全可靠)

利用Sequelize的参数绑定功能,自动处理字符串的引号转义和SQL注入防护:

async editControls(req, res) {
    try {
      const { id, controlsCode, controlsName } = req.body;

      // 用命名参数绑定,可读性更强
      const query = `update controls set controlCode=:controlsCode, controlName=:controlsName where id=:id`;
      await sequelize
        .query(query, {
          replacements: { id, controlsCode, controlsName }
        })
        .then((item) =>
          this.response({ res, message: "ok", data: controlsCode })
        )
        .catch((error) => console.log(error.message));
    } catch (error) {
      console.log(error.message);
    }
}

也可以使用位置参数:

const query = `update controls set controlCode=$1, controlName=$2 where id=$3`;
await sequelize.query(query, {
  replacements: [controlsCode, controlsName, id]
})

参数化查询是处理SQL语句的标准安全方案,既能解决字符串字段的引号问题,又能有效防范SQL注入,建议优先采用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:57:52