试图按属性选择一个条目(id,user_name,foo,bar,等等);
这是我的socketing代码;
socket.on('database attribute', function(msg) {
queryDriver.getAllEntriesByAttribute(gatheringstable, 'user_name', 'john', function(err, gatherings) {
console.log(gatherings);
io.emit('database attribute', gatherings);
});
});
这是我的数据库驱动程序代码;
QueryDriver.prototype.getAllEntriesByAttribute = function(table, attribute, value, callback) {
this.dbclient.query('SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + value, function(err, result) {
if(err) {
callback(err);
}
else {
callback(null, result.rows);
}
});
};
如果我们看一下这个SQL命令的典型语句,它看起来像"SELECT * FROM table WHERE attribute='value';"
。这将从数据库中提取具有'john'的'user_name'属性的条目。
这适用于我的'heroku pg:psql' daemon.
由于某些原因,这在我的代码中不起作用,除非我在命令中更改'value'和'attribute'的位置。像这样;
socket.on('database attribute', function(msg) {
queryDriver.getAllEntriesByAttribute(gatheringstable, 'john', 'user_name', function(err, gatherings) {
console.log(gatherings);
io.emit('database attribute', gatherings);
});
});
然后它将适用于我的heroku实现,我可以调用它并获得[{"id":1,"user_name":"john"}]
但它拒绝在我的'heroku pg:psql'守护程序中工作。
我是否发现了世界上最良性的SQL错误?
现实崩溃了吗?
为什么这反过来? "user_name"="john"
是你称之为的实际方式,但"john"="user_name"
是唯一对我有用的正确方式。
更改:
'SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + value
至
'SELECT * FROM ' + table + ' WHERE "' + attribute + '"=' + value
在你的驱动程序代码中,我应该让你使用“正确”的命令。
如果你检查true / false 1 = 2或2 = 1,那么对于sql没什么区别,所以“标准”命令确实是人类偏好,而不是更多
我通过执行以下操作来修复它。
守护进程里面我测试了两个命令;
SELECT * FROM test_table WHERE 'user_name' = 'john'
哪个返回“null”
SELECT * FROM test_table WHERE user_name = 'john'
哪个返回“1列”
虽然Vao Tsun的答案很接近,但实际上并没有解决这个问题,但它给了我一个关于该做什么的简洁暗示。
这是正确的实施;
QueryDriver.prototype.getAllEntriesByAttribute = function(table, attribute, value, callback) {
this.dbclient.query('SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + "'" + value + "'", function(err, result) {
if(err) {
callback(err);
}
else {
callback(null, result.rows);
}
});
};
这相当于做第二个命令,
SELECT * FROM test_table WHERE user_name = 'john'
所以ATTRIBUTE不能用引号括起来,VALUE必须用引号括起来。
Vao Tsun的答案很接近,但仅在您没有引用文本值时才有效。如果要查找具有文本值的列,则不得使用引号转义该属性。你必须逃避价值。
因此,
[{"id":1,"user_name":"john"}]