2015-06-24 48 views
1

嘗試按屬性(id,user_name,foo,bar,whatever)選擇條目;Node.js SQL Server代碼似乎是錯誤的,但仍然有效?

這是我的插件代碼;

socket.on('database attribute', function(msg) { 
 
\t \t queryDriver.getAllEntriesByAttribute(gatheringstable, 'user_name', 'john', function(err, gatherings) { 
 
\t \t \t console.log(gatherings); 
 
\t \t \t io.emit('database attribute', gatherings); 
 
\t \t }); 
 
\t });

這裏是我的數據庫驅動程序代碼;

QueryDriver.prototype.getAllEntriesByAttribute = function(table, attribute, value, callback) { 
 
\t this.dbclient.query('SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + value, function(err, result) { 
 
\t \t if(err) { 
 
\t \t \t callback(err); 
 
\t \t } 
 
\t \t else { 
 
\t \t \t callback(null, result.rows); 
 
\t \t } 
 
\t }); 
 
};

如果我們看一看這個SQL命令一個典型發言,它看起來像"SELECT * FROM table WHERE attribute='value';"。這將從數據庫中拉出'john'的'user_name'屬性。

這工作我'heroku pg:psql' daemon.

這並不在我的代碼工作,出於某種原因,除非我改變的「價值」,並在命令「屬性」的位置。喜歡這個;

socket.on('database attribute', function(msg) { 
 
\t \t queryDriver.getAllEntriesByAttribute(gatheringstable, 'john', 'user_name', function(err, gatherings) { 
 
\t \t \t console.log(gatherings); 
 
\t \t \t io.emit('database attribute', gatherings); 
 
\t \t }); 
 
\t });

然後,它會工作得很好,爲我的Heroku的實現,我可以打電話,並得到[{"id":1,"user_name":"john"}],但它拒絕在我的工作「的Heroku PG:psql的」守護進程。

我發現了世界上最良性的SQL錯誤嗎?

現實是否分崩離析?

爲什麼這個工作相反? "user_name"="john"是您可以稱之爲的實際方式,但"john"="user_name"是適用於我的唯一正確方式。

+0

順便說一句,執行console.log(ERR);會幫助很多 –

回答

0

我做固定它以下。

守護進程內部我測試了兩個命令;

SELECT * FROM test_table WHERE 'user_name' = 'john' 

哪個返回「空」

SELECT * FROM test_table WHERE user_name = 'john' 

哪個返回「1列」

雖然維羅樽的答案是接近,它實際上並沒有解決這方面的問題,但它給了我關於做什麼的簡潔提示。

正確的實現是這樣的;

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"}] 
2

變化:

'SELECT * FROM ' + table + ' WHERE ' + attribute + '=' + value 

'SELECT * FROM ' + table + ' WHERE "' + attribute + '"=' + value 
在驅動程序代碼

,應該讓你用 「正確」 的順序,我猜。

BTW對SQL沒有區別,如果你檢查真/假1 = 2或2 = 1,讓「非標準」爲了確實是一個人的偏愛,而不是更多

+0

等什麼?我不明白是什麼意思。在我的查詢代碼中沒有引號(「) – ARMATAV

+1

我把它寫成了相反的:)我的意思是你要嘗試在列名稱周圍加雙引號 –

+0

啊,我會在我回家的時候試試這個,會讓你知道的 – ARMATAV

相關問題