Node MySQL escape LIKE statement

旧时模样 提交于 2019-11-30 07:24:44

问题


How do escape a MySQL LIKE statement in node-mysql?

Something along the lines of

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

Results in

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

Which is a syntax error. If I use the alternative syntax of

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

Results in a similar syntax error. I've also tried

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

Which just ends up escaping the '%' sign.


回答1:


Not sure why it's escaping the % in your last example, because that works fine for me:

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

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

When I turn on debugging in the driver (pass debug:true as argument to mysql.createConnection), it doesn't escape the percent sign:

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

(it does escape the single quote, but that's for display purposes only)

(using mysql@2.0.0-alpha8)




回答2:


i've had success with something like

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



回答3:


How about

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

?



来源:https://stackoverflow.com/questions/17922587/node-mysql-escape-like-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!