fe-interview
fe-interview copied to clipboard
[js] 第165天 举例说明如何使用WebSQL?
第165天 举例说明如何使用WebSQL?
var dbName = 'project';
// 版本
var version = 1;
// 数据库数据结果
var db;
// 打开数据库
var DBOpenRequest = window.indexedDB.open(dbName, version);
// 如果数据库打开失败
DBOpenRequest.onerror = function(event) {
console.warn('数据库打开失败');
};
DBOpenRequest.onsuccess = function(event) {
// 存储数据结果
db = DBOpenRequest.result;
};
// 下面事情执行于:数据库首次创建版本,或者window.indexedDB.open传递的新版本(版本数值要比现在的高)
DBOpenRequest.onupgradeneeded = function(event) {
var db = event.target.result;
db.onerror = function(event) {
console.warn('数据库打开失败');
};
// 创建一个数据库存储对象
var objectStore = db.createObjectStore(dbName, {
keyPath: 'id',
autoIncrement: true
});
// 定义存储对象的数据项
objectStore.createIndex('id', 'id', {
unique: true
});
objectStore.createIndex('name', 'name');
objectStore.createIndex('begin', 'begin');
objectStore.createIndex('end', 'end');
objectStore.createIndex('remark', 'remark');
};
var method = {
add: function (newItem) {
var transaction = db.transaction([dbName], "readwrite");
// 打开已经存储的数据对象
var objectStore = transaction.objectStore(dbName);
// 添加到数据对象中
var objectStoreRequest = objectStore.add(newItem);
objectStoreRequest.onsuccess = function(event) {
console.log('插入成功')
};
},
edit: function (id, data) {
// 编辑数据
var transaction = db.transaction([dbName], "readwrite");
// 打开已经存储的数据对象
var objectStore = transaction.objectStore(dbName);
// 获取存储的对应键的存储对象
var objectStoreRequest = objectStore.get(id);
// 获取成功后替换当前数据
objectStoreRequest.onsuccess = function(event) {
// 当前数据
var myRecord = objectStoreRequest.result;
// 遍历替换
for (var key in data) {
if (typeof myRecord[key] != 'undefined') {
myRecord[key] = data[key];
}
}
// 更新数据库存储数据
objectStore.put(myRecord);
};
},
del: function (id) {
// 打开已经存储的数据对象
var objectStore = db.transaction([dbName], "readwrite").objectStore(dbName);
// 直接删除
var objectStoreRequest = objectStore.delete(id);
// 删除成功后
objectStoreRequest.onsuccess = function() {
console.log('删除成功')
};
}
};
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "菜鸟教程")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.runoob.com")');
msg = '<p>数据表已创建,且插入了两条数据。</p>';
document.querySelector('#status').innerHTML = msg;
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>查询记录条数: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
});
var db = openDatabase("mydb")