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 }

最佳答案

您将单引号放在查询字符串的错误位置。更改此:

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


...对此:

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


...这样第二个百分号在单引号内。

如果要进行注释中提到的“开头为”搜索,请从字段值的开头删除'%'

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


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

10-04 22:18