Using INDEXEDDB (ii) (translation)

Source: Internet
Author: User

Inserting, querying, deleting data

Before you take any action on the newly created database, you need to open a transaction. The transaction originates from the database object, and you must specify the object store to be covered by the transaction. Once you enter a transaction, you have access to the object store to manipulate the data and create the request. Next, you need to decide whether to change the database or read the contents of the database. There are three valid modes for a transaction: read-only, read-write, and version changed.

Changing the database schema or structure-involves creating or deleting an object store or index--must have the transaction in version change Versionchange mode. Open the transaction by calling Idbfactory.open and specifying a version number. (WebKit Browser, no perfect up-to-date INDEXEDDB version, Idbfactory.open can only carry one parameter: database name; then you must call Idbversionchangerequest.setversion to establish Versionchange transaction).

In order to read the records in the object store, a transaction can use either ReadOnly mode or ReadWrite mode. If you want to change the record, the transaction must be in ReadWrite mode. You call the Idbdatabase.transaction () function to

Transaction, the function accepts two parameters, Storenames (scope, defined as an array of object store types that you will access), Pattern mode (readonly or ReadWrite). The function returns a transaction object that contains the Dbindex.objectstore method, which you can use to access the object store. By default, transactions are opened in readonly mode.

Note: Starting with firefox40, the INDEXEDDB transaction has relaxed durability in order to improve performance. Previously, in a read-write transaction, only if all data

Idbtransaction.oncomplete is triggered when both are written to disk. In firefox40 and later versions, the operating system is told to start writing data, but implicitly, the OnComplete event is triggered before the data is fully written to the disk.

The correct setting of scopes and patterns for transactions can improve data access performance, with the following key points:

When defining scopes, specify only the object store you need, so that you can run multiple transactions without overlapping (scope) at the same time

Specify read-write ReadWrite mode only when necessary. You can run multiple readonly transactions at the same time (scope), but only one object store can run ReadWrite transactions.

Inserting data

If you create a new database, you may want to write data. As shown below:

var transaction = db.transaction(["customers"], "readwrite");// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".// In case you want to support such an implementation, you can write: // var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);

The transaction () function has two parameters and returns a transaction object. The first parameter is the list of objects that the transaction covers, (that is, the scope of the transaction).

If you want the transaction to cover all the object stores, you can specify an empty array here, but don't do that because the specification says that an empty array throws a invalidaccesserror error. If you do not specify a second parameter, the read-only mode is used by default. If you want to write a database, please specify it as ReadWrite.

Now that you have created the transaction, you need to know its lifetime. Transactions are tightly bound to the event loop. If you create a transaction and return to the event loop,

However, if it is not used, then the transaction becomes inactive. The only way to keep a transaction alive is to create a request on it. When the request is complete,

You will get a DOM event that will make the request successful and you will have a new opportunity to extend the transaction in the callback function. If you return to the transaction loop without extending the transaction, the transaction becomes inactive, and so on. The transaction remains active as long as there is a waiting period pending request. The lifetime of a transaction is really simple, but it still takes some time to master it. A few more examples will also help to understand. If you have started reading

The Transaction_inactive_err error code is not appropriate (because the lifetime of the transaction has not been understood).

Transactions can be divided into three kinds of DOM events: Error,abort, and complete. We have discussed the way the error event is bubbling, so the transaction accepts any error event thrown from the request it produces. More subtly,

The default behavior of the error event is to abort the transaction in which it resides. The transaction is rolled back unless you first call Stoppropagation () in error handling and then perform other processing. Such a design can force the need to consider and handle errors, but

If error handling is too lengthy and trivial, you can bind an error handle to the database object. If you do not handle the error event, or if the abort () function is called on the transaction, the transaction is rolled back, and the transaction's rollback event is triggered.

Or, all of the waiting period pending requests are processed. You will get a complete event. If you perform a large number of database operations, tracking transactions instead of individual requests will help you clarify your thinking.

Now that you have a transaction, you need to get the object store from it. A transaction simply gives you the object store that you specified when you created the transaction. You can then add data to the object store.

Do something if all the data was added to the database.transaction. oncomplete=function(Event){Alert("All done!");}; transaction. onerror=function(Event){Don ' t forget to handle errors!};var ObjectStore= Transaction.ObjectStore("Customers");For(var iin customerdata) { span class= "token keyword" >var request = objectstore.< Span class= "token function" >add (Customerdata[i< Span class= "token punctuation" >]) .onsuccess = function (Event{//event.target.result = = CUSTOMERDATA[I].SSN; };}     

The call to the Add () method results in the value of the "key" being added. In this case, it should be equal to the SSN property of the object being added, because the object store
Use the SSN attribute as the keypath. Note that the Add () method requires that an object with the same "key" cannot exist in the database. If you try to change an already existing object, or if you do not care if the object exists, you can call the put () method, as shown in the Updating a entry in the database.

Delete data

Deleting data is simple:

var request= db.Transaction(["Customers"]objectstore ( "Customers ") . Delete (;request= function ( Event{//It ' s gone! }       

Querying data

Now that you have the data in the database, you can query the data in several ways. First, the simplest get () method. You need to provide "key" to query the number
It is like this:

VAR transaction= db.Transaction(["Customers"]);var ObjectStore= Transaction.ObjectStore("Customers");var request= ObjectStore.Get("444-44-4444"); request. onerror=function(Event{//Handle errors!< Span class= "token punctuation" >};request= function ( Event{//do Something with the request.result! alert ( "Name for SSN 444-44-4444 is "+ request.result.name" ;}             

There's a lot of code for a "simple" query. Here you can make it a little bit shorter, assuming you handled the error message at the database level:

Db.Transaction("Customers").ObjectStore("Customers". Get ( "444-44-4444" .onsuccess = function (Event{alert (" Name for SSN 444-44-4444 is "+ event.target.result< Span class= "token punctuation" >.name) ;}         

See how it works? Because there is only one object store, you do not have to pass the object store list, only the name of the object store to the transaction. And
You are simply querying the database, so you do not need ReadWrite mode. The default mode for calling the transaction () method is readonly. The other subtle point
Is that you don't really have to save the request to a variable. Because the DOM event takes the request requests as its target, you can use Event.target to replace request.


Note that the data access speed can be increased by restricting the scope scope of the transaction, and the mode of the transaction.

Update data
Now that we have some data, it's easy to update it and insert the INDEXEDDB database. Let's change the previous example:

var ObjectStore= db.Transaction(["Customers"],"ReadWrite").ObjectStore("Customers");var request= ObjectStore.Get("444-44-4444"); request. onerror=function(Event){Handle errors!}; request. onsuccess=function(Event){Get the old value then we want to updatevar data= Event. Target. Result;Update the value (s) in the "object" and "want to" change data. Age=42;Put this updated object back into the database.var requestupdate= ObjectStore.Put(Data . onerror = function ( Event{//do Something with the error } Requestupdate.onsuccess = function (Event{ //success-the data is updated! };}             

Here we create a objectstore, request to read a data record, use the "key" value ssn:444-44-4444. Then the query results are stored in the
Variable data, change the value of the age property of the variable data, and then create a request to write the changed data back to the database, overwriting the original result.

Note: At this point, we must specify the transaction for the ReadWrite mode, because the database content is to be written, not just the query data

Using INDEXEDDB (ii) (translation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.