2014-12-05 40 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

相关问题