如何在类似查询的Knex中转义%? [英] How do I escape % in Knex where like query?

查看:73
本文介绍了如何在类似查询的Knex中转义%?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用knex生成我的SQL查询.在knex文档中,它显示了此内容

I'm using knex to generate my SQL queries. In knex documentation, it shows this

knex('users').where('columnName', 'like', '%rowlikeme%')

现在在我的应用程序中,我这样做了:

Now in my application, I did this:

function search(term) {
  term = "%" + term + "%";
  knex('table').where('description', 'like', term);
  // ...
}

我如何转义%,以便它也搜索%作为术语的一部分?

How can I escape % so that it searches for % as part of the term as well?

谢谢.

推荐答案

在这种情况下,我使用

es6(安全版本)中的相当字符串内插

rather string interpolation from es6 (safe version)

knex('table').where('description', 'like', `%${term}%`)

??参数绑定

knex('table').whereRaw('description like \'%??%\'', [term])

但是在第一种情况下,由于 SQL注入的可能性.

But in the first case, you must be 100% sure that term is valid, because of the possibility of SQL injection.

这篇关于如何在类似查询的Knex中转义%?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆