javascript - 通过 Knex.js 执行 POSTGRES LIKE 时出现语法错误
问题描述
这给了我一个语法错误:
if (searchCode) {
customerProducts = await customerProducts.andWhere(
db.sequelize.knex.raw('customer.code LIKE '
+ `%${searchCode}%`)
);
}
}
错误如下所示:
{"message":"UnknownErrorMiddleware error: select \"CustomerProduct\".\"id\" as \"_id\", \"CustomerProduct\".\"last_delivered\" as \"_lastDelivered\", \"CustomerProduct\".\"margin\" as \"_margin\", \"CustomerProduct\".\"outlier\" as \"_outlier\", \"CustomerProduct\".\"growth\" as \"_growth\", \"CustomerProduct\".\"period\" as \"_period\", \"CustomerProduct\".\"price\" as \"_price\", \"CustomerProduct\".\"active\" as \"_active\", \"CustomerProduct\".\"customer_id\" as \"_customerId\", \"CustomerProduct\".\"product_id\" as \"_productId\", \"CustomerProduct\".\"modified\" as \"_modified\", \"CustomerProduct\".\"month_value\" as \"_monthValue\", \"customer\".\"id\" as \"_customer_id\", \"customer\".\"title\" as \"_customer_title\", \"customer\".\"code\" as \"_customer_code\" from \"customer_products\" as \"CustomerProduct\" inner join \"customers\" as \"customer\" on \"CustomerProduct\".\"customer_id\" = \"customer\".\"id\" where \"product_id\" = $1 and customer.code LIKE %ZOO1% - syntax error at or near \"%\"","level":"info"}
我认为问题在于''
周围没有,%ZOO1%
但我不知道如何添加它。它是如何完成的,如果这不是问题,那是什么?
解决方案
您可以像这样添加它们'%${searchCode}%'
。但是searchCode
变量会容易出现sql注入。
不过,您应该使用原始参数绑定功能
db.sequelize.knex.raw('customer.code LIKE ?', [`%${searchCode}%`])
推荐阅读
- java - 无法正确中断递归代码
- node.js - 在不刷新页面的情况下响应获取请求
- python - 从字典而不是文件路径设置 ["GOOGLE_APPLICATION_CREDENTIALS"]
- css - 在 div 中使用带有 wrap 的 flex 列占用所有剩余空间
- typescript - “对任何值的不安全成员访问”TypeScript 错误
- linux - linux输出,不需要终端输出
- rust - 这行中的双冒号是什么意思?
- julia - 如何在 Julia 中调整贝叶斯 ODE 的超参数?
- java - Java 读取 JSON 属性名称而不解析为类
- python - AttributeError:“int”对象没有带有饼图的属性“plot”