用 idbc 操作数据库
时间: 2024-05-13 19:16:26 浏览: 18
IDBC (IndexedDB) 是一种本地浏览器数据库,允许在浏览器中存储和检索数据。下面是一个使用 IDBC 操作数据库的示例:
```javascript
// 打开数据库
let request = indexedDB.open('myDatabase', 1);
// 如果数据库不存在则创建
request.onupgradeneeded = function(event) {
let db = event.target.result;
let objectStore = db.createObjectStore('customers', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
};
// 打开成功后执行回调函数
request.onsuccess = function(event) {
let db = event.target.result;
// 添加数据
let tx = db.transaction('customers', 'readwrite');
let objectStore = tx.objectStore('customers');
objectStore.add({ id: 1, name: 'John Doe', age: 30 });
tx.oncomplete = function() {
console.log('Data added successfully.');
};
// 读取数据
let tx2 = db.transaction('customers', 'readonly');
let objectStore2 = tx2.objectStore('customers');
let index = objectStore2.index('name');
let request = index.get('John Doe');
request.onsuccess = function() {
console.log(request.result.age);
};
};
```
在这个示例中,我们首先打开数据库并创建一个名为 "customers" 的对象仓库,该仓库包含一个名为 "id" 的键和一个名为 "name" 的索引。之后,我们添加了一条数据并读取了该数据。注意,添加数据和读取数据都需要在事务中完成。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)