node.js mysql LIKE语句用法

时间:2017-04-12 03:36:04

标签: javascript mysql node.js

app.post('/like/:level/:name', function(req, res){
connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) {
if (!err){
var row = rows;
res.send(row);
console.log(req.params);
 console.log('The solution is: ', rows);}
else{
 console.log('Error while performing Query.');
console.log(err);}
});
});

根据上面的代码,有人可以帮我找到为什么我不能使用LIKE语句启动查询的原因吗?

the error is shown as
    { Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%' at line 1
    at Query.Sequence._packetToError (/root/Newfolder/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
    at Query.ErrorPacket (/root/Newfolder/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
    at Protocol._parsePacket (/root/Newfolder/node_modules/mysql/lib/protocol/Protocol.js:280:23)
    at Parser.write (/root/Newfolder/node_modules/mysql/lib/protocol/Parser.js:75:12)
    at Protocol.write (/root/Newfolder/node_modules/mysql/lib/protocol/Protocol.js:39:16)
    at Socket.<anonymous> (/root/Newfolder/node_modules/mysql/lib/Connection.js:103:28)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    --------------------
    at Protocol._enqueue (/root/Newfolder/node_modules/mysql/lib/protocol/Protocol.js:141:48)
    at Connection.query (/root/Newfolder/node_modules/mysql/lib/Connection.js:208:25)
    at /root/Newfolder/trial.js:98:12
    at Layer.handle [as handle_request] (/root/Newfolder/node_modules/express/lib/router/layer.js:95:5)
    at next (/root/Newfolder/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/root/Newfolder/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/root/Newfolder/node_modules/express/lib/router/layer.js:95:5)
    at /root/Newfolder/node_modules/express/lib/router/index.js:281:22
    at param (/root/Newfolder/node_modules/express/lib/router/index.js:354:14)
    at param (/root/Newfolder/node_modules/express/lib/router/index.js:365:14)
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlState: '42000',
  index: 0 }

2 个答案:

答案 0 :(得分:1)

您的查询字符串中的单引号位于错误的位置。改变这个:

" like '%" + req.params.name + "'%"

......对此:

" like '%" + req.params.name + "%'"

...以便第二个百分号在单引号内。

如果您想按照评论中的提法进行“搜索”,请从字段值的开头删除'%'

" like '" + req.params.name + "'%"

最后,不是你问的问题,而是你shouldn't directly concatenate user input into an SQL query

答案 1 :(得分:0)

简单的方法:

SELECT * from books where ${req.params.level} LIKE '${req.params.name}%'

我认为这要干净得多。