Using IndexedDB when my app first runs I populate it with some data, I want to ensure that when the database and tables are created that they do not already exists.
Can I query the length of a table to see if it contains and data in JavaScript?
Using IndexedDB when my app first runs I populate it with some data, I want to ensure that when the database and tables are created that they do not already exists.
Can I query the length of a table to see if it contains and data in JavaScript?
Share Improve this question edited May 21, 2012 at 15:55 Peter Aron Zentai 11.7k6 gold badges42 silver badges72 bronze badges asked May 21, 2012 at 14:35 CLiownCLiown 13.8k50 gold badges127 silver badges205 bronze badges 1- CLiown, toske has the correct answer please accept it if it solves your case. – Deni Spasovski Commented Dec 5, 2013 at 20:04
4 Answers
Reset to default 8We can use the objectStoreNames property of IndexDB to check the existence of an ObjectStore.
var db_object, object_store;
if( !db.objectStoreNames.contains(currentobjectstore) )
{
db_object = i_db.createObjectStore(currentobjectstore, {autoIncrement:true} );
object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
} else {
object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
}
Best way is trying to open objectStore in try catch block. It is synchronous also. In case of an error you can create store for example:
var store;
try {
store = request.transaction.objectStore('yourStore');
}
catch(e) {
store = db.createObjectStore('yourStore');
}
You can use objectStore.count() function, but i recommend storing some kind of meta-data that would say that your local db is initialized. Otherwise, you can have page-reload in middle of data creation and never have your data fully synced with remote data.
The database is created if a database with the specified name does not exist else it opens it
eg.var request = indexedDB.open("DataTbl");
So if your db already exists it will just open it and about you checking if the contents in the table already exists then you can make an xyz objectstore and store some key/value flag pair inside it saying that the insertion was successful and check it later everytime when page is reloaded.
Also you can give at try to count function specified by @toske
ref :
http://www.ibm.com/developerworks/library/wa-indexeddb/
http://www.w3.org/TR/IndexedDB/