Indexeddb 简明教程
IndexedDB - Connection
数据库是一个有序的、结构化数据集合,这些数据存储在计算机系统中。为了对数据执行操作,我们需要连接到数据库。在本章中,我们将讨论如何创建/连接到数据库、打开数据库和删除数据库。
A database is an organized collection of structured data stored in a computer system. To perform operations on data we need to connect to a database. In this chapter, we will discuss how to create/connect to a database, open a database, and delete a database.
Creating a database - 你可以使用 open() 函数在 IndexedDB 中创建一个数据库。以下是此函数的语法。
Creating a database − You can create a database in IndexedDB using the open() function. Following is the syntax of this function.
let openRequest = indexedDB.open(name, version);
其中,
Where,
-
name is the name of the database you need to create.
-
version is the version of the database that is to be created. The default value of this parameter is 1. If you omit this value, the version is considered as 1.
你要传递给此函数的版本值不应低于当前版本(IndexedDB 的版本)。如果成功创建了数据库,则此函数返回 1;如果创建失败,则返货 0。
The version value you pass to this function should not be less than the current version (of the IndexedDB). This function returns 1 if the database is created successfully and it returns 0 in case of a failure.
Example
以下是 IndexedDB 中创建数据库的示例:
Following is the example to create a database in IndexedDB
<!DOCTYPE html>
<html lang="en">
<head>
<title>Indexed db</title>
</head>
<body>
<script>
//Creating a database
const request = indexedDB.open("myDatabase", 1);
if(indexedDB){
document.write("Database Created......");
}
</script>
</body>
</html>
Output
如果您把上面的代码保存在文件“ test.html ”中并运行它,浏览器将显示以下消息:
If you save the above code in a file “test.html” and run it, the following message will be displayed on the browser −
Database Created......
Verification
因为 IndexedDB 是浏览器内置的数据库,所以在浏览器中就能看到创建的数据库。
Since IndexedDB is the browser’s built-in database you observe the created database in the browser itself.
右键点击生成页面,点击“检查元素”并选取“应用标签”。如果展开此选项卡,您可以在其中看到 IndexedDB 数据库,您可以看到创建的数据库文件,如下所示:
Right-click on the resultant page, click on inspect element and select the Application tab. You can see the IndexedDB database there if you expand it you can see the created database file as shown below −

Generating Handlers
event 是在 HTML 元素上执行的操作。我们可以使用 JavaScript 处理这些事件。从现在开始,我们将使用 JavaScript 处理程序(为了让此更清楚)。
An event is an action performed on an HTML element. Using JavaScript we can handle these events. From now on we use JavaScript handlers (to make this clearer).
如果请求成功,我们将使用 onsuccess 事件。
If the request is a success, we use the onsuccess event.
request.onerror = event => {
// Do something (ex: document.write("error");
};
如果请求失败,我们将使用 onerror 事件。
If the request is a failure, we use onerror event.
request.onsuccess = event => {
// Do something (ex : document.write("success");
};
当创建一个数据库或增加现有数据库的版本号时,我们将使用 onupgradeneeded 事件。
When you create a database or increase the version number of an existing database we use onupgradeneeded event.
request.onupgradeneeded = event => {
var db = event.target.result;
};
Example
以下示例显示消息“ database creation success ”。如果数据库创建成功。在这里,我们使用 onsuccess 和 onerror 处理程序来显示这些消息。
Following example displays the message “database creation success”. If the database creation is successful. In here we are using the onsuccess and onerror handlers to display these messages.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Handlers</title>
</head>
<body>
<script>
const request = indexedDB.open("DATABASE", 1);
request.onsuccess = function (){
document.write("Database created successfully...")
}
request.onerror = function(){
document.write("database creation error");
}
request.onupgradeneeded = function(event){
var db = event.target.result;
}
</script>
</body>
</html>
Connecting to an existing database
为了与 IndexedDB 交互,我们使用 JavaScript。我们用 JavaScript 撰写的代码并不会直接与数据库交互。我们需要使用连接对象连接到数据库,以操作数据库的对象。
To interact with IndexedDB, we use JavaScript. The code we write in JavaScript doesn’t interact with databases directly. We need to connect with the database using a connection object to manipulate the objects of the database.
直接打开数据库会创建一个连接。一个数据库可以有多个连接。当创建连接之初,它处于打开状态。
Opening a database directly creates a connection. There can be multiple connections to a database. When a connection is initially created it is in the open state.
您可以使用 open() 函数连接到 IndexedDB 数据库(我们用来创建数据库)。
You can connect to an IndexedDB database using the open() function (which we used to create a database).
Syntax
下面是连接到现有数据库的语法。
Following is the syntax to connect to an existing database.
let openRequest = indexedDB.open(name, version);
Example
下面给出了一个使用带有连接对象的 JavaScript 示例,它与现有数据库交互:
A JavaScript example that interacts with an existing database using a connection object is given below −
<!DOCTYPE html>
<html lang="en">
<head>
<title>OPENING A DATABASE</title>
</head>
<body>
<script>
const request = indexedDB.open("DATABASE", 1);
request.onsuccess = function (){
document.write("<br> Database created successfully")
}
const requestone = indexedDB.open("Database1",2);
requestone.onsuccess = function(){
document.write("<br> Database created successfully");
}
const requesttwo = indexedDB.open("DATABASE",1);
requesttwo.onsuccess = function(){
document.write("<br> Database opened successfully");
}
</script>
</body>
</html>
Another way to check databases in the browser
除了检查元素之外,还有另一种方法可以在浏览器中检查 IndexedDB 数据库。
In addition to the inspect element, there is another way to check the IndexedDB database in the browser.
在右上角将有一个“自定义和控制”按钮,点击它。
In the top right corner, there will be a customize and control button, Click it.
在列表中选择 More tools 选项,然后选择 Developer tools 。
Select the More tools option in the list and then select Developer tools.

在下一页中选择“应用程序”选项卡,您可以在其中看到 IndexedDB 数据库。
On the next page select the Application tab where you can see the IndexedDB database.

Deleting a database
如果有我们不需要的或没有必要占用空间的任何数据库,我们可以将其删除。要删除数据库,我们可以使用 deleteDatabase() 函数。
If there is an excess of any database which we do not need or it unnecessarily occupies space, we can delete it. To delete a database we can use the deleteDatabase() function.
以下是 deleteDatabase() 函数的语法 −
Following is the syntax of the deleteDatabase() function −
let deleteRequest = indexedDB.deleteDatabase(name)
这里, name 参数是我们想要删除的数据库的名称。
Here, the name parameter is the name of the database that we want to delete.
Example
以下示例创建了一个名为 TestDatabase 的数据库并使用 deleteDatabase() 函数将其删除。
Following example creates a database named TestDatabase and deletes it using the deleteDatabase() function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Indexed db</title>
</head>
<body>
<script>
const request = indexedDB.open("TestDatabase", 1);
request.onsuccess = function () {
document.write("Database Created Successfully");
};
var req = indexedDB.deleteDatabase("TestDatabase");
req.onsuccess = function () {
document.write("Database Deleted Successfully");
};
req.onerror = function () {
document.write("Couldn't delete the database");
};
</script>
</body>
</html>
Deleting a database Directly From the browser
创建数据库后,您可以直接从浏览器中删除它。要执行此操作,请按照以下步骤操作 −
Once you create a database, you can directly delete it database from the browser. To do so, follow the steps given below −
Step 1 − 使用以下方式之一在浏览器中打开可以看到 IndexedDB 数据库(存储)的页面
Step 1 − Open the page where you can see the IndexedDB database (storage) in the browser, using one of the following ways
-
Inspect option − Right−click → Inspect → Application or,
-
Developer tools − Customize and Control Options → More tools → Developers tools → Application
Step 2 − 如果您展开 IndexedDB 存储,可以看到如下图所示的已创建数据库列表。
Step 2 − If you expand the IndexedDB storage, you can observe the list of databases created as shown below.

Step 3 − 单击要删除的数据库。在右侧,您将找到 Delete Database 按钮。如果单击它,将删除此数据库。
Step 3 − Click on the database you want to delete. On the right−hand side, you will find the Delete Database button. If you click on it, this database will be deleted.

Closing a database
要关闭数据库,我们需要使用函数 IDBDatabase.close()
To close a database we need to use the function IDBDatabase.close()
Syntax
IDBDatabase.close();
IDBDatabase 接口的 close() 方法会立即返回并关闭连接。
The close() method of the IDBDatabase interface returns immediately and closes the connection.
在所有事务都完成之前,连接并未关闭,但是无法对此连接创建新事务,并且如果挂起关闭操作,方法会引发异常。
The connection is not closed until all transactions are complete but, new transactions cannot be created for this connection and methods throw exceptions if the closing operation is pending.