[英]Node.js SQL Server code seems to be wrong, but still works?
嘗試按屬性(id,user_name,foo,bar等)選擇條目;
這是我的套接字代碼;
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.
由於某些原因,這在我的代碼中不起作用,除非我更改命令中“值”和“屬性”的位置。 像這樣;
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
在驅動程序代碼中,我猜應該讓您使用“正確”的命令。
BTW for sql如果檢查true / false 1 = 2或2 = 1,則沒有區別,因此,“ standart”順序實際上是人為偏好,而不是更多
我通過執行以下操作修復了該問題。
在守護程序內部,我測試了兩個命令:
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'
因此, 屬性一定不能用引號引起來, 值一定不能用引號引起來。
Vao Tsun的答案很接近,但僅當您未引用文本值時才有效。 如果要查找帶有文本值的列,則不得使用引號將屬性轉義。 您必須轉義該值。
因此,
[{"id":1,"user_name":"john"}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.