indexedDB数据库的使用
<!DOCTYPE html> <html> <head> <title>indexedDB数据库的使用</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="button" value="连接数据库" onclick="connectDatabase()"> <input type="button" value="创建对象仓库" onclick="CreateObjectStore()"> <input type="button" value="保存数据" onclick="SaveData()"> <input type="button" value="读取数据" onclick="GetData()"> <script> window.indexedDB=window.indexedDB || window.webkitIndexedDB|| window.mozIndexedDB||window.msIndexedDB; window.IDBTransaction=window.IDBTransaction||window.webkitIDBTransaction||window.msIDBTransaction; window.IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange||window.msIDBKeyRange; window.IDBCursor=window.IDBCursor||window.webkitIDBCursor||window.msIDBCursor; //连接数据库 function connectDatabase(){ var request = indexedDB.open('dbName', 1); // 打开 dbName 数据库 request.onerror = function(e){ // 监听连接数据库失败时执行 console.log('连接数据库失败'); } request.onsuccess = function(e){ // 监听连接数据库成功时执行 console.log('连接数据库成功'); } } function CreateObjectStore(){ var request = indexedDB.open('dbName', 3); request.onupgradeneeded = function(e){ var db = e.target.result; var store = db.createObjectStore('Users', {keyPath: 'userId', autoIncrement: false}); console.log('创建对象仓库成功'); } } function SaveData(){ var request = indexedDB.open('dbName', 5); request.onsuccess = function(e){ var db = e.target.result; var tx = db.transaction('Users','readwrite'); var store = tx.objectStore('Users'); var value = { 'userId': 1, 'userName': 'linxin', 'age': 24 } var req = store.put(value); req.onsuccess=function(){ console.log("数据保存成功"); } req.onerror=function(){ console.log("数据保存失败"); } } } function GetData(){ var request = indexedDB.open('dbName', 6); request.onsuccess = function(e){ var db = e.target.result; var tx = db.transaction('Users','readwrite'); var store = tx.objectStore('Users'); var range = IDBKeyRange.bound(0,10); var req = store.openCursor(range, 'next'); req.onsuccess = function(){ var cursor = this.result; if(cursor){ console.log(cursor.value.userName); cursor.continue(); }else{ console.log('检索结束'); } } } } </script> </body> </html>