Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1118027 of IDBDatabase

  • Revision slug: Web/API/IDBDatabase
  • Revision title: IDBDatabase
  • Revision id: 1118027
  • Created:
  • Creator: Sheppy
  • Is current revision? Yes
  • Comment

Revision Content

{{APIRef("IndexedDB")}}

The IDBDatabase interface of the IndexedDB API provides a connection to a database; you can use an IDBDatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.

{{AvailableInWorkers}}

Note: Everything you do in IndexedDB always happens in the context of a transaction, representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.

Methods

Inherits from: EventTarget

{{domxref("IDBDatabase.close()")}}
Returns immediately and closes the connection to a database in a separate thread.
{{domxref("IDBDatabase.createObjectStore()")}}
Creates and returns a new object store or index.
{{domxref("IDBDatabase.deleteObjectStore()")}}
Destroys the object store with the given name in the connected database, along with any indexes that reference it.
{{domxref("IDBDatabase.transaction()")}}
Immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store. Runs in a separate thread.

Properties

{{domxref("IDBDatabase.name")}} {{readonlyInline}}
A {{ domxref("DOMString") }} that contains the name of the connected database.
{{domxref("IDBDatabase.version")}} {{readonlyInline}}
A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string.
{{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}
A {{ domxref("DOMStringList") }} that contains a list of the names of the object stores currently in the connected database.

Event handlers

{{domxref("IDBDatabase.onabort")}}
Fires when access of the database is aborted.
{{domxref("IDBDatabase.onclose")}}
Fires when the {{event("close")}} event occurs; this happens when the database is unexpectedly closed, such as during application shutdown.
{{domxref("IDBDatabase.onerror")}}
Fires when access to the database fails.
{{domxref("IDBDatabase.onversionchange")}}

Fires when a database structure change ({{domxref("IDBOpenDBRequest.onupgradeneeded")}} event or {{domxref("IDBFactory.deleteDatabase()")}} was requested elsewhere (most probably in another window/tab on the same computer). This is different from the version change transaction (see {{domxref("IDBVersionChangeEvent")}}), but it is related.

Example

In the following code snippet, we open a database asynchronously ({{domxref("IDBFactory")}}), handle success and error cases, and create a new object store in the case that an upgrade is needed ({{ domxref("IDBdatabase") }}). For a complete working example, see our To-do Notifications app (view example live.)

// Let us open our database
  var DBOpenRequest = window.indexedDB.open("toDoList", 4);

  // these two event handlers act on the IDBDatabase object, when the database is opened successfully, or not
  DBOpenRequest.onerror = function(event) {
    note.innerHTML += '<li>Error loading database.</li>';
  };
 
  DBOpenRequest.onsuccess = function(event) {
    note.innerHTML += '<li>Database initialised.</li>';
    
    // store the result of opening the database in the db variable. This is used a lot later on
    db = DBOpenRequest.result;
    
    // Run the displayData() function to populate the task list with all the to-do list data already in the IDB
    displayData();
  };
 
  // This event handles the event whereby a new version of the database needs to be created
  // Either one has not been created before, or a new version number has been submitted via the
  // window.indexedDB.open line above
 
  DBOpenRequest.onupgradeneeded = function(event) {
    var db = event.target.result;
    
    db.onerror = function(event) {
      note.innerHTML += '<li>Error loading database.</li>';
    };

    // Create an objectStore for this database using IDBDatabase.createObjectStore
    
    var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
    
    // define what data items the objectStore will contain
    
    objectStore.createIndex("hours", "hours", { unique: false });
    objectStore.createIndex("minutes", "minutes", { unique: false });
    objectStore.createIndex("day", "day", { unique: false });
    objectStore.createIndex("month", "month", { unique: false });
    objectStore.createIndex("year", "year", { unique: false });

    objectStore.createIndex("notified", "notified", { unique: false });
    
    note.innerHTML += '<li>Object store created.</li>';
  };

This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.

    var objectStore = db.transaction('toDoList').objectStore('toDoList'); 

Specifications

Specification Status Comment
{{SpecName('IndexedDB', '#idl-def-IDBDatabase', 'IDBDatabase')}} {{Spec2('IndexedDB')}} Initial version
{{SpecName("IndexedDB 2", "#database-interface", "IDBDatabase")}} {{Spec2("IndexedDB 2")}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko)[1] Internet Explorer Opera Safari (WebKit)
Basic support 23 {{property_prefix("webkit")}}
24
10 {{property_prefix("moz")}}
{{CompatGeckoDesktop(16)}}
10, partial 15 7.1
Available in workers {{CompatVersionUnknown}} {{CompatGeckoDesktop(37)}} {{CompatUnknown}} {{CompatVersionUnknown}} {{CompatUnknown}}
{{event("close")}} event {{CompatUnknown}} {{CompatGeckoDesktop(50)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}
Feature Android Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile
Basic support 4.4 {{CompatGeckoMobile(22)}} 1.0.1 10 22 8
Available in workers {{CompatVersionUnknown}} {{CompatGeckoMobile(37)}} {{CompatVersionUnknown}} {{CompatUnknown}} {{CompatVersionUnknown}} {{CompatUnknown}}
{{event("close")}} event {{CompatUnknown}} {{CompatGeckoMobile(50)}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

[1] As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}). Previously in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}).

See also

  • Using IndexedDB
  • Starting transactions: {{domxref("IDBDatabase")}}
  • Using transactions: {{domxref("IDBTransaction")}}
  • Setting a range of keys: {{domxref("IDBKeyRange")}}
  • Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
  • Using cursors: {{domxref("IDBCursor")}}
  • Reference example: To-do Notifications (view example live.)

 

Revision Source

<p>{{APIRef("IndexedDB")}}</p>

<div>
<p>The <strong><code>IDBDatabase</code></strong> interface of the IndexedDB API provides a <a href="/en-US/docs/IndexedDB#database_connection">connection to a database</a>; you can use an <code>IDBDatabase</code> object to open a <a href="/en-US/docs/IndexedDB#gloss_transaction">transaction</a> on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.</p>

<p>{{AvailableInWorkers}}</p>
</div>

<div class="note">
<p><strong>Note</strong>: Everything you do in IndexedDB always happens in the context of a <a href="/en-US/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB#gloss_transaction">transaction</a>, representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.</p>
</div>

<h2 id="Methods">Methods</h2>

<p>Inherits from: <a href="/en-US/docs/DOM/EventTarget">EventTarget</a></p>

<dl>
 <dt>{{domxref("IDBDatabase.close()")}}</dt>
 <dd>Returns immediately and closes the connection to a database in a separate thread.</dd>
 <dt>{{domxref("IDBDatabase.createObjectStore()")}}</dt>
 <dd>Creates and returns a new object store or index.</dd>
 <dt>{{domxref("IDBDatabase.deleteObjectStore()")}}</dt>
 <dd>Destroys the object store with the given name in the connected database, along with any indexes that reference it.</dd>
 <dt>{{domxref("IDBDatabase.transaction()")}}</dt>
 <dd>Immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store. Runs in a separate thread.</dd>
</dl>

<h2 id="Properties">Properties</h2>

<dl>
 <dt>{{domxref("IDBDatabase.name")}} {{readonlyInline}}</dt>
 <dd>A {{ domxref("DOMString") }} that contains the name of the connected database.</dd>
 <dt>{{domxref("IDBDatabase.version")}} {{readonlyInline}}</dt>
 <dd>A <a href="/en-US/docs/NSPR_API_Reference/Long_Long_(64-bit)_Integers">64-bit integer</a> that contains the version of the connected database. When a database is first created, this attribute is an empty string.</dd>
 <dt>{{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}</dt>
 <dd>A {{ domxref("DOMStringList") }} that contains a list of the names of the <a href="/en-US/docs/IndexedDB#gloss_object_store">object stores</a> currently in the connected database.</dd>
</dl>

<h3 id="Event_handlers">Event handlers</h3>

<dl>
 <dt>{{domxref("IDBDatabase.onabort")}}</dt>
 <dd>Fires when access of the database is aborted.</dd>
 <dt>{{domxref("IDBDatabase.onclose")}}</dt>
 <dd>Fires when the {{event("close")}} event occurs; this happens when the database is unexpectedly closed, such as during application shutdown.</dd>
 <dt>{{domxref("IDBDatabase.onerror")}}</dt>
 <dd>Fires when access to the database fails.</dd>
 <dt>{{domxref("IDBDatabase.onversionchange")}}</dt>
 <dd>
 <p>Fires when a database structure change ({{domxref("IDBOpenDBRequest.onupgradeneeded")}} event or<code> </code>{{domxref("IDBFactory.deleteDatabase()")}} was requested elsewhere (most probably in another window/tab on the same computer). This is different from the version change transaction (see {{domxref("IDBVersionChangeEvent")}}), but it is related.</p>
 </dd>
</dl>

<h2 id="example" name="example">Example</h2>

<p>In the following code snippet, we open a database asynchronously ({{domxref("IDBFactory")}}), handle success and error cases, and create a new object store in the case that an upgrade is needed ({{ domxref("IDBdatabase") }}). For a complete working example, see our <a href="https://github.com/mdn/to-do-notifications/">To-do Notifications</a> app (<a href="https://mdn.github.io/to-do-notifications/">view example live</a>.)</p>

<pre class="brush: js;highlight:[13,24,26,27,28,32]">
// Let us open our database
  var DBOpenRequest = window.indexedDB.open("toDoList", 4);

  // these two event handlers act on the IDBDatabase object, when the database is opened successfully, or not
  DBOpenRequest.onerror = function(event) {
    note.innerHTML += '&lt;li&gt;Error loading database.&lt;/li&gt;';
  };
 
  DBOpenRequest.onsuccess = function(event) {
    note.innerHTML += '&lt;li&gt;Database initialised.&lt;/li&gt;';
    
    // store the result of opening the database in the db variable. This is used a lot later on
    db = DBOpenRequest.result;
    
    // Run the displayData() function to populate the task list with all the to-do list data already in the IDB
    displayData();
  };
 
  // This event handles the event whereby a new version of the database needs to be created
  // Either one has not been created before, or a new version number has been submitted via the
  // window.indexedDB.open line above
 
  DBOpenRequest.onupgradeneeded = function(event) {
    var db = event.target.result;
    
    db.onerror = function(event) {
      note.innerHTML += '&lt;li&gt;Error loading database.&lt;/li&gt;';
    };

    // Create an objectStore for this database using IDBDatabase.createObjectStore
    
    var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
    
    // define what data items the objectStore will contain
    
    objectStore.createIndex("hours", "hours", { unique: false });
    objectStore.createIndex("minutes", "minutes", { unique: false });
    objectStore.createIndex("day", "day", { unique: false });
    objectStore.createIndex("month", "month", { unique: false });
    objectStore.createIndex("year", "year", { unique: false });

    objectStore.createIndex("notified", "notified", { unique: false });
    
    note.innerHTML += '&lt;li&gt;Object store created.&lt;/li&gt;';
  };</pre>

<p>This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.</p>

<pre class="brush: js">
    var objectStore = db.transaction('toDoList').objectStore('toDoList'); </pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('IndexedDB', '#idl-def-IDBDatabase', 'IDBDatabase')}}</td>
   <td>{{Spec2('IndexedDB')}}</td>
   <td>Initial version</td>
  </tr>
  <tr>
   <td>{{SpecName("IndexedDB 2", "#database-interface", "IDBDatabase")}}</td>
   <td>{{Spec2("IndexedDB 2")}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)<sup>[1]</sup></th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>23 {{property_prefix("webkit")}}<br />
    24</td>
   <td>10 {{property_prefix("moz")}}<br />
    {{CompatGeckoDesktop(16)}}</td>
   <td>10, partial</td>
   <td>15</td>
   <td>7.1</td>
  </tr>
  <tr>
   <td>Available in workers</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop(37)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td>{{event("close")}} event</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoDesktop(50)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE Phone</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>4.4</td>
   <td>{{CompatGeckoMobile(22)}}</td>
   <td>1.0.1</td>
   <td>10</td>
   <td>22</td>
   <td>8</td>
  </tr>
  <tr>
   <td>Available in workers</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile(37)}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td>{{event("close")}} event</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoMobile(50)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}). Previously in a <code>readwrite</code> transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the <code>complete</code> event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The <code>complete</code> event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further. If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the <code>complete</code> event by creating a transaction using the experimental (non-standard) <code>readwriteflush</code> mode (see {{domxref("IDBDatabase.transaction")}}).</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a></li>
 <li>Starting transactions: {{domxref("IDBDatabase")}}</li>
 <li>Using transactions: {{domxref("IDBTransaction")}}</li>
 <li>Setting a range of keys: {{domxref("IDBKeyRange")}}</li>
 <li>Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}</li>
 <li>Using cursors: {{domxref("IDBCursor")}}</li>
 <li>Reference example: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="https://mdn.github.io/to-do-notifications/">view example live</a>.)</li>
</ul>

<p>&nbsp;</p>
Revert to this revision