【问题标题】:NodeJS MySQL errorNodeJS MySQL错误
【发布时间】:2018-11-14 21:54:30
【问题描述】:

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 用于所有 Posts 的列,不包括 Post_ID

console.log(err);没有错误记录。

有消息: 当我将 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 没有按预期工作。

【问题讨论】:

  • 这只是引用的问题。由于您在关键字中传递了一个字符串,因此您必须将其用引号括起来
  • keyword 是 NodeJS 变量。
  • 并且关键字必须用引号括起来,这样当您将其转换为要在 SQL 中解析的值时,您就不会遇到这个问题
  • 让我试试...
  • 尝试直接在数据库中运行查询,看看它是否应该返回任何结果(通过回显应用程序生成的 sql 代码替换关键字的值)

标签: mysql node.js node-mysql


【解决方案1】:

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

"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 值以关键字结尾;
  • keyword%值以keyword开头;
  • %keywords% 值包含关键字的某处

如果你不使用通配符,那么使用 LIKE 是没有用的

【讨论】:

  • 试过了,MySQL没有返回错误,但如果它是正确的,那么它应该给我结果,但它给出的是空的json。
猜你喜欢
  • 2016-09-10
  • 2023-04-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多