javascript 节点 MySQL 转义 LIKE 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17922587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node MySQL escape LIKE statement
提问by dtsn
How do escape a MySQL LIKE statement in node-mysql?
如何在 node-mysql 中转义 MySQL LIKE 语句?
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.
最终逃脱了“%”符号。
回答by robertklep
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:
当我在驱动程序中打开调试(debug:true
作为参数传递给mysql.createConnection
)时,它不会转义百分号:
{ command: 3,
sql: 'SELECT * from django_session where session_key like \'%ee20e966289cd7%\'' }
(it doesescape the single quote, but that's for display purposes only)
(它确实逃脱了单引号,但这仅用于显示目的)
(using [email protected]
)
回答by Gary
i've had success with something like
我在类似的事情上取得了成功
"SELECT * FROM card WHERE name LIKE " + connection.escape('%'+req.body.search+'%')
回答by Lukasz Prus
How about
怎么样
mysql.format("SELECT * FROM card WHERE name LIKE CONCAT('%', ?, '%')", req.body.search)
?
?
回答by Rodrigo Pazzini Jacques
you can always do
你总能做到
variable = '%${variable}%'
"SELECT * FROM 'table' WHERE ('foo' LIKE ?);",
[variable], callback =>