mysql - 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
没有按预期工作。
解决方案
您需要将传递给查询的值用引号括起来。所以对你来说正确的语法应该是:
"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 是没有用的
推荐阅读
- c# - EF 核心不允许我两次访问相同的属性
- c# - 在 DataGrid 中设置 UserControl 的属性?
- python - 多列的 Pandas Groupby Multiindex
- java - android studio 不接受获取 Instance() 方法来获取 Firebase 数据
- javascript - 如何使用 react-query 将来自不同 react-query 钩子的数据同步连接在一起?
- python - python 3中GUI的抽象网格
- html - 在 Rails 中加载注册页面时自动填充表单字段
- reactjs - 如何使用 Google 作为提供者来阻止 React Native Maps 的 Draggable Marker 在 iOS 上禁用 MapView 之外的触摸?
- mongodb - 通过 MongoDB Kafka 连接器使用多个集合
- javascript - 未捕获的语法错误:使用 express 时无法在模块外部使用 import 语句