簡體   English   中英

如何在不知道sqlite3 node.js中的列名的情況下獲取記錄值

[英]how to get record values without knowing column names in sqlite3 node.js

考慮以下sqlite3 nodejs代碼

db.each("SELECT rowid AS id, item FROM SampleTable", function(err, row) {
  return console.log(row);
});

這將在控制台中打印以下內容

{ id: 1, item: 'Item #0' }
{ id: 2, item: 'Item #1' }
{ id: 3, item: 'Item #2' }
{ id: 4, item: 'Item #3' }
{ id: 5, item: 'Item #4' }
{ id: 6, item: 'Item #5' }
{ id: 7, item: 'Item #6' }
{ id: 8, item: 'Item #7' }
{ id: 9, item: 'Item #8' }
{ id: 10, item: 'Item #9' }

我想不使用列名即不使用row.id和row.item來獲取記錄值(1 2 3 ...&Item#0,Item#1 ...)。 我的實際項目本質上是非常動態的,並且處理多個數據庫中的不同表。 因此,不可能知道列名。

我在node-sqlite3 Wiki https://github.com/mapbox/node-sqlite3/wiki/API中找到了以下內容

It is impossible to access them by column index; the only supported way is by column name.

我想知道在不使用列名的情況下是否有任何方法來獲取記錄值。 我能找到的最接近的是以下內容。 循環並使用jQuery獲取JSON數組的鍵/值對

您可以使用for / in獲取列名(或行對象屬性)。

使用函數按索引訪問屬性:

//col is a 0-based column index
function getRowColumn(row, col) {
     for (p in row) {
         if (col==0) return row[p];
         --col;
     }
}

因此,您可以使用:

... getRowColumn(row, 0) ...
... getRowColumn(row, 1) ...
... getRowColumn(row, 2) ...

在最近的瀏覽器上,可以使用此解決方案通過列索引訪問行數據: row[Object.keys(columnIndex)]

將對象展平為數組也可以for

 function rowArray(row) {
     var a=[];
     for(var m in row) a.push(row[m]);
     return a;
 }

因此,您可以使用:

db.each("SELECT rowid AS id, item FROM SampleTable", function(err, row) {
     return console.log(rowArray(row));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM