2014-12-05 74 views
0

我對indexedDB相當陌生,並開始創建一個數據庫來傳輸WebSQL。如何在索引數據庫上創建列/對象

我想知道的是如何在indexedDB中創建字段。

例如:

tx.executeSql("CREATE TABLE IF NOT EXISTS TEMPRESULTENTRIES (" 
    + " id INTEGER PRIMARY KEY AUTOINCREMENT, " 
    + " instid INTEGER NOT NULL REFERENCES institutions(id) ON DELETE CASCADE, " 
    + " qid INTEGER NOT NULL REFERENCES questionnaires(id) ON DELETE CASCADE, " 
    + " result TEXT NOT NULL)"); 

我怎麼會在IndexedDB的創建相同的表。我對這部分indexedDB感到困惑。 目前,我與ID創建唯一的keyPath:

db.createObjectStore("TEMPRESULTENTRIES", {keypath: "id", autoIncrement: true}); 

而且我想知道如何添加,或者將要創建的其他領域?

從一個小的測試用例,我可以看到,我可以只創建列/在存儲中的對象時,我ANM填充表/存儲,如:

store.put({ObjectName: Value}); 

是不是正確的方法來創建在賣場對象?

最佳,Amry

回答

1

索引資料是一個面向對象的數據庫,而不是關係數據庫。與SQL表最接近的模擬是對象庫,使用IDBDatabase.createObjectStore創建。對象存儲沒有固定的模式,因此只要對象具有keyPath字段或者通過設置{autoIncrement: true}使keyPath變爲可選,對IDBObjectStore.put的調用就可以接受具有任何字段的對象。默認情況下,您只能使用keyPath查詢文檔。要使用其他字段查詢文檔,必須使用IDBObjectStore.createIndex

創建索引這是從使用數字或名稱的前綴查找聯繫人的應用程序的摘錄。

dbReq.onupgradeneeded = function (event) { 
    var db = event.target.result, 
     objectStore = db.createObjectStore('calls', {keyPath: 'timestamp'}), 
     contactStore = db.createObjectStore('contacts', {autoIncrement: true}); 

    objectStore.createIndex('number', 'number', {unique: false}); 
    contactStore.createIndex('number', 'number'); 
    contactStore.createIndex('name', 'name', {unique: false}); 
    objectStore.createIndex('timestamp', 'timestamp', {unique: true}); 
}; 

查找前綴:

findPrefix: function(prefix, fn) { 
    var transaction = this.db.transaction(['contacts', 'calls']), 
     contactStore = transaction.objectStore('contacts'), 
     callStore = transaction.objectStore('calls'), 
     numberIndex = callStore.index('number'), 
     nameIndex = contactStore.index('name'), 
     key = IDBKeyRange.bound(prefix, prefix + '\uffff'), 
     times = 0, 
     result = [], 
     consume = function(records) { 
      result = result.concat(records); 
      if (++times === 2) { 
       /* Remove duplicate numbers: names and numbers may have the same value*/ 
       var numbers = {}; 
       result = result.filter(function(contact) { 
        if (!numbers[contact.number]) { 
         return (numbers[contact.number] = true); 
        } 
        return false; 
       }); 
       fn(result); 
      } 
     }; 

    this.consumeCursor(numberIndex.openCursor(key, 'nextunique'), consume); 
    this.consumeCursor(nameIndex.openCursor(key), consume); 
} 

More on IndexedDB

+0

所以有其他的對象領域,我需要在創建時的ObjectStore爲,首先創建的keyPath?糾正我,如果我錯了。 – amol01 2014-12-05 12:42:50

+0

不,對象存儲中最多隻能有一個'keyPath'字段。 'keyPath'字段用於查找對象,並且必須是唯一的。您可以將任何字段的對象添加到對象存儲中,而無需重新塑造對象存儲。也就是說,'objectStore.put({keyPathField:1,f1:2,f2:3})'和'objectStore.put({keyPathField:2,g1:[1,3],g2:3})'都是允許。如果在字段中沒有任何索引,則只能使用'keyPath'字段的值查找對象存儲:'IDBObjectStore.get(2)'將產生{keyPathField:2,g1:[1,3 ],g2:3}' – 2014-12-05 13:02:45

+0

感謝您的澄清。如果你能回答,我可以在onupgradeneeded函數上創建幾個對象存儲嗎?當我第一次創建數據庫和對象庫? – amol01 2014-12-05 13:06:34