36

如何在 node-mysql 中转义 MySQL LIKE 语句?

类似的东西

"SELECT * FROM card WHERE name LIKE '%" + connection.escape(req.body.search) + "%'"

结果是

'SELECT * FROM card WHERE name LIKE \'%\'hello\'%\''

这是一个语法错误。如果我使用替代语法

connection.query("SELECT * FROM card WHERE name LIKE '%?%'", req.body.search, function () {});

导致类似的语法错误。我也试过

connection.query("SELECT * FROM card WHERE name LIKE ?", '%' + req.body.search + '%', function () {});

最终会转义“%”符号。

4

6 回答 6

40

不知道为什么它%在你的最后一个例子中转义,因为这对我来说很好:

// lifted from my code:
var value = 'ee20e966289cd7';
connection.query('SELECT * from django_session where session_key like ?', '%' + value + '%', ...)

// Result:
[ { session_key: '713ee20e966289cd71b936084a1e613e', ... } ]

当我在驱动程序中打开调试(debug:true作为参数传递给mysql.createConnection)时,它不会转义百分号:

{ command: 3,
  sql: 'SELECT * from django_session where session_key like \'%ee20e966289cd7%\'' }

(它确实转义了单引号,但这仅用于显示目的)

(使用mysql@2.0.0-alpha8

于 2013-07-29T11:22:58.520 回答
19

我在类似的事情上取得了成功

"SELECT * FROM card WHERE name LIKE " + connection.escape('%'+req.body.search+'%')
于 2016-01-06T04:57:39.083 回答
6

怎么样

mysql.format("SELECT * FROM card WHERE name LIKE CONCAT('%', ?,  '%')", req.body.search)

?

于 2018-11-18T18:19:33.503 回答
0

你总能做到

variable = '%${variable}%'
"SELECT * FROM 'table' WHERE ('foo' LIKE ?);", 
[variable], callback =>
于 2020-01-13T21:14:04.660 回答
0

我遇到了同样的问题并像这样解决了它:

function search(searchTerm) {

    let replacement = `'%${searchTerm}%'`;

    let sqlStatement = `SELECT * from  clients where firstName LIKE ${replacement}`;

    const [rows, fields, error] = connection.query(sqlStatement);

    return rows;

}
于 2021-01-09T22:46:04.343 回答
0

简单易行的方法:

`SELECT * FROM card WHERE name LIKE ` + connection.escape(`%${req.body.search}%`)
于 2021-08-28T18:03:24.837 回答