javascript - SQLITE 查询的“排序依据”结果未排序
问题描述
我正在做一个网上商店项目。我正在尝试根据 sqlite 数据库中的参数值获取排序结果。我正在尝试根据“选择”值对产品进行排序。
在我的 app.js
app.get('/sortMaleProducts', function(request, response){
var sortValues = request.query.sortValue;
if(sortValues == 'priceASC')
{
sortValues = ["man", "price", "ASC"];
}
else if(sortValues == 'priceDESC')
{
sortValues = ["man", "price", "DESC"];
}
db.sortMaleProducts(sortValues, function(error, clothes){
if(error){
console.log("Error: "+ error);
}
else{
console.log(clothes)
const model = {
clothes
}
response.render("man.hbs", model)
}
})
})
在我的 db.js
exports.sortMaleProducts = function(sortValues, callback){
const query = 'SELECT * FROM products WHERE gender = ? Order by ?, ?'
db.all(query, sortValues, function(error, clothes){
console.log(clothes);
callback(error, clothes);
})
如果我对查询进行硬编码,例如:
const query = 'SELECT * FROM products WHERE gender = 'man' Order by price ASC'
然后它就可以工作了……但是我想使用用户输入,这样我就可以重用代码……
解决方案
如果要按列排序,则该列名必须直接出现在查询中。您正在执行的操作按字符串'price'
和对结果进行排序'ASC'
,这对于每一行都是相同的,因此对结果的任何顺序都进行了排序。
您也不能在查询中的其他任何地方使用列名作为参数,例如在要返回的列中或在WHERE
. 当通过将语句编译成 sqlite 的内部字节码来准备语句时,它们必须存在,这发生在任何参数绑定或执行查询之前。
推荐阅读
- gcc - X86中mov和movl指令的区别?我在阅读汇编时遇到了一些麻烦
- erlang - 具有精确键列表的模式匹配映射
- keycloak - Keycloak登录页面:重定向到另一个客户端
- php - Laravel 过滤器和身份验证
- performance - 好吗,采样时间随着用户数量的增加而逐渐增加
- python - Python XML 文件仅获取具有多个标签的子元素
- python - Python - 多线程访问的锁类
- matlab - linux上的matlab:线图不起作用
- javascript - CodeIgniter - 将表单中动态添加的输入字段中的值存储到 MySQL 表中
- python-3.x - IndexError:索引 10 超出轴 1 的范围,大小为 10