首页 > 解决方案 > NodeJS MySQL错误

问题描述

NodeJS代码如下:

    app.get('/search', function(req, res){
    var keyword = req.query.q;
    con.query("SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date FROM Posts WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC", function (err, result) {
    if (err){
    console.log("Error on DB SELECT.");
    console.log(err);
    tellSelectError(req, res);
}else{
    console.log("Database selected");
    console.log(result);
    /*res.render('index', {
        info: info,
        result: result
    });*/
    res.json(result);
    }
});
});

它将空 json 发送到客户端浏览器。

截图上传于:https ://i.stack.imgur.com/kpSDA.jpg

请帮助.....这段代码正在工作: SELECT * FROM Posts WHERE Post_ID = " + keyword但我想将LIKE用于除Post_ID之外的所有Posts列。

控制台日志(错误);记录没有错误。

得到一个消息:当我将 SQL 更改为 时SELECT * FROM Posts,它正确返回所有原始数据,但SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date FROM Posts WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC没有按预期工作。

标签: mysqlnode.jsnode-mysql

解决方案


您需要将传递给查询的值用引号括起来。所以对你来说正确的语法应该是:

"SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date 
FROM Posts 
WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC"

注意:LIKE 是一个运算符,用于代替 = 来搜索字段内的值。= 将尝试匹配整个字段。为此,LIKE 在三个不同的选项中使用通配符 (%):

  • %keyword 值以关键字结尾;
  • 关键字% 值以关键字开头;
  • %keywords% 该值在某处包含关键字

如果您不使用通配符,则使用 LIKE 是没有用的


推荐阅读