In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article shows you how to get started with the browser database IndexedDB, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
I. Overview
With the continuous enhancement of the functionality of browsers, more and more websites begin to consider storing a large amount of data on the client, which can reduce access to data from the server and directly from the local data.
Existing browser data storage solutions are not suitable for storing large amounts of data: Cookie is no larger than 4KB, and every request is sent back to the server; LocalStorage is between 2.5MB and 10MB (different browsers), and does not provide search function, can not build a custom index. Therefore, a new solution is needed, which is the background of the birth of IndexedDB.
In popular terms, IndexedDB is a local database provided by a browser that can be created and manipulated by web scripts. IndexedDB allows you to store large amounts of data, provide a lookup interface, and build indexes. These are what LocalStorage does not have. As far as the database type is concerned, IndexedDB is not a relational database (SQL query statements are not supported) and is closer to the NoSQL database.
IndexedDB has the following characteristics.
Key-value pairs are stored. IndexedDB uses object Warehouse (object store) to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, the data is saved in the form of "key-value pairs". Each data record has a corresponding primary key. The primary key is * *, and there can be no repetition, otherwise an error will be thrown.
Asynchronous. IndexedDB does not lock the browser, and users can still perform other operations, in contrast to LocalStorage, which operates synchronously. Asynchronous design is designed to prevent the reading and writing of a large amount of data and slow down the performance of web pages.
Support transactions. IndexedDB supports transactions (transaction), which means that in a series of operation steps, as long as one step fails, the entire transaction is cancelled, the database is rolled back to the state before the transaction occurred, and there is no case of rewriting only part of the data.
The same origin restriction IndexedDB is subject to the same origin restriction, and each database corresponds to the domain name in which it is created. The web page can only access the database under its own domain name, not the cross-domain database.
Large storage space IndexedDB has much more storage space than LocalStorage, generally no less than 250MB, or even no upper limit.
Support for binary storage. IndexedDB can store not only strings but also binary data (ArrayBuffer objects and Blob objects).
II. Basic concepts
IndexedDB is a relatively complex API, involving many concepts. It abstracts different entities into object interfaces. To learn this API is to learn its various object interfaces.
Databases: IDBDatabase object
Object repository: IDBObjectStore object
Indexes: IDBIndex object
Transactions: IDBTransaction object
Operation request: IDBRequest object
Pointers: IDBCursor object
Primary key collections: IDBKeyRange object
Here are some major concepts.
Database
A database is a container for a series of related data. Each domain name (strictly speaking, protocol + domain name + port) can create as many databases as you want.
IndexedDB database has the concept of version. Only one version of the database can exist at a time. If you want to modify the database structure (add or delete tables, indexes, or primary keys), you can only do so by upgrading the database version.
Object warehouse
Each database contains several object repositories (object store). It is similar to a table in a relational database.
Data recording
The object warehouse holds data records. Each record is similar to the row of a relational database, but only has two parts: the primary key and the data body. The primary key is used to establish the default index, which must be different, otherwise an error will be reported. The primary key can be an attribute in the data record, or it can be specified as an incremental integer number.
{id: 1, text: 'foo'}
In the above object, the id property can be used as the primary key.
The data body can be of any data type and is not limited to objects.
Indexes
To speed up data retrieval, you can index different properties in the object repository.
Business
The reading, writing and deletion of data records are completed through transactions. The transaction object provides three events, error, abort, and complete, to listen for the result of the operation.
III. Operation process
The various operations of the IndexedDB database are generally carried out in accordance with the following process. This section only gives a simple code example for getting started quickly. See here for detailed API of each object.
Open the database
The * * step in using IndexedDB is to open the database and use the indexedDB.open () method.
Var request = window.indexedDB.open (databaseName, version)
This method accepts two parameters, and the * parameters are strings that represent the name of the database. If the specified database does not exist, a new database is created. The second parameter is an integer that represents the version of the database. If omitted, the default is the current version when you open an existing database and 1 when you create a new database.
The indexedDB.open () method returns an IDBRequest object. This object handles the result of opening the database through three events, error, success, and upgradeneeded.
Error event
The error event indicates a failure to open the database.
Request.onerror = function (event) {console.log ('database open error');}
Success event
The success event indicates that the database was opened successfully.
Var db; request.onsuccess = function (event) {db = request.result; console.log ('database opened successfully');}
At this point, the database object is obtained through the result property of the request object.
Upgradeneeded event
If the specified version number is greater than the actual version number of the database, the database upgrade event upgradeneeded occurs.
Var db; request.onupgradeneeded = function (event) {db = event.target.result;}
At this point, the database instance is obtained through the target.result property of the event object.
Create a new database
Creating a new database is the same operation as opening the database. If the specified database does not exist, a new one is created. The difference is that the subsequent operation is mainly done in the listener function of the upgradeneeded event, which is triggered because the version starts from scratch.
Usually, after you create a new database, the * thing to do is to create a new object repository (that is, a new table).
Request.onupgradeneeded = function (event) {db = event.target.result; var objectStore = db.createObjectStore ('person', {keyPath:' id'});}
In the above code, after the database is created successfully, a new table called person is added, and the primary key is id.
A better way to write is to determine whether the form exists or not, and then create a new one if it doesn't.
Request.onupgradeneeded = function (event) {db = event.target.result; var objectStore; if (! db.objectStoreNames.contains ('person')) {objectStore = db.createObjectStore (' person', {keyPath: 'id'});}}
The primary key (key) is the default indexed attribute. For example, if the data record is {id: 1, name: 'Zhang San'}, then the id attribute can be used as the primary key. The primary key can also be specified as a property of the next layer object, such as the foo.bar of {foo: {bar: 'baz'}}.
If there are no attributes in the data record that are suitable for the primary key, you can have IndexedDB generate the primary key automatically.
Var objectStore = db.createObjectStore ('person', {autoIncrement: true})
In the above code, the primary key is specified as an incremental integer.
After creating a new object repository, the next step is to create a new index.
Request.onupgradeneeded = function (event) {db = event.target.result; var objectStore = db.createObjectStore ('person', {keyPath:' id'}); objectStore.createIndex ('name',' name', {unique: false}); objectStore.createIndex ('email',' email', {unique: true});}
In the above code, the three parameters of IDBObject.createIndex () are the name of the index, the property where the index is located, and the configuration object (indicating whether the property contains duplicate values).
New data
New data refers to writing data records to the object repository. This needs to be done through transactions.
Function add () {var request = db.transaction (['person'],' readwrite') .objectStore ('person') .add ({id: 1, name:' Zhang San', age: 24, email: 'zhangsan@example.com'}); request.onsuccess = function (event) {console.log (' data written successfully');} Request.onerror = function (event) {console.log ('data write failed');}} add ()
In the above code, writing data requires a new transaction. You must specify a table name and mode of operation (read-only or read-write) when you create a new one. After creating a new transaction, get the IDBObjectStore object through the IDBTransaction.objectStore (name) method, and then write a record to the table through the add () method of the table object.
A write operation is an asynchronous operation that listens to the connection object's success and error events to see if the write was successful.
Read data
Reading data is also done through transactions.
Function read () {var transaction = db.transaction (['person']); var objectStore = transaction.objectStore (' person'); var request = objectStore.get (1); request.onerror = function (event) {console.log ('transaction failure');}; request.onsuccess = function (event) {if (request.result) {console.log ('Name:' + request.result.name) Console.log ('Age:' + request.result.age); console.log ('Email:' + request.result.email);} else {console.log ('no data record');}};} read ()
In the above code, the objectStore.get () method is used to read the data, and the argument is the value of the primary key.
Ergodic data
To traverse all records of the data table, use the pointer object IDBCursor.
Function readAll () {var objectStore = db.transaction ('person'). ObjectStore (' person'); objectStore.openCursor (). Onsuccess = function (event) {var cursor = event.target.result; if (cursor) {console.log ('Id:'+ cursor.key); console.log ('Name:' + cursor.value.name); console.log ('Age:' + cursor.value.age) Console.log ('Email:' + cursor.value.email); cursor.continue ();} else {console.log ('no more data!') ;}};} readAll ()
In the above code, the openCursor () method of the new pointer object is an asynchronous operation, so listen for the success event.
Update data
Use the IDBObject.put () method to update the data.
Function update () {var request = db.transaction (['person'],' readwrite') .objectStore ('person') .put ({id: 1, name:' Li Si', age: 35, email: 'lisi@example.com'}); request.onsuccess = function (event) {console.log (' data updated successfully');} Request.onerror = function (event) {console.log ('data update failed');}} update ()
In the above code, the put () method automatically updates the record with a primary key of 1.
Delete data
The IDBObjectStore.delete () method is used to delete records.
Function remove () {var request = db.transaction (['person'],' readwrite') .objectStore ('person') .delete (1); request.onsuccess = function (event) {console.log (' data deleted successfully');};} remove ()
Use index
The meaning of the index is that it allows you to search for any field, that is, to get the data record from any field. If you do not index, by default you can only search for the primary key (that is, take values from the primary key).
Assume that the name field is indexed when you create a new table.
ObjectStore.createIndex ('name',' name', {unique: false})
Now you can find the corresponding data record from name.
Var transaction = db.transaction (['person'],' readonly'); var store = transaction.objectStore ('person'); var index = store.index (' name'); var request = index.get ('Li Si'); request.onsuccess = function (e) {var result = e.target.result If (result) {/ /...} else {/ /}} the above content is how the browser database IndexedDB is introduced. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.