Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - Node MySQL escape LIKE statement

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 [email protected])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...