节点MySQL转义LIKE语句

时间:2013-07-29 11:14:40

标签: javascript mysql node.js node-mysql

如何在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 () {});

最终逃脱了'%'登录。

5 个答案:

答案 0 :(得分:29)

不确定为什么它会在你上一个例子中转移%,因为这对我来说很好用:

// 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

答案 1 :(得分:12)

我已经取得了类似

之类的成功
"SELECT * FROM card WHERE name LIKE " + connection.escape('%'+req.body.search+'%')

答案 2 :(得分:0)

怎么样

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

答案 3 :(得分:0)

您随时可以

function ExampleWithManyStates() {

    const initialState = 0;

    const [age, setAge] = useState(initialState);
    const [count, setCount] = useState(initialState);
    ...
    const [price, setPrince] = useState(initialState);

答案 4 :(得分: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;

}