因indexedDB的API接口功能比较单一,不能进行较为复杂的与或非运算,为了方便使用对indexedDB进行了一次封装,使之支持多重条件运算以及自定义排序!
使用方法
引用相应js文件到页面,并打开数据库(如果数据库不存在会先自动创建数据库再打开)
<script src="indexedDB.js"></script>
<script type="text/javascript" charset="utf-8">
TJ_DB.openDB('DBName', function(db) {
// 如果表不存在,创建表
if (!db.objectStoreNames.contains('tableName')) {
var objectStore = db.createObjectStore('tableName', {
keyPath: 'id'
});
// 指定可以被索引的字段(unique表示字段值是否唯一)
objectStore.createIndex('shopId', 'shopId', {
unique: false
});
objectStore.createIndex('name', 'name', {
unique: false
});
objectStore.createIndex('info', 'info', {
unique: false
});
objectStore.createIndex('read', 'read', {
unique: false
});
}
}, function(result) {
console.log(result);
});
</script>
添加数据
<script type="text/javascript" charset="utf-8">
var data = [
{
"id": 4,
"shopId": 2,
"name": "AK",
"info": "说明0",
"read": true
},
{
"id": 5,
"shopId": 1,
"name": "王小丫",
"info": "说明1111",
"read": false
},
{
"id": 6,
"shopId": 1,
"name": "老李",
"info": "这是一段说明",
"read": true
}
];
TJ_DB.add('tableName', data, function(result) {
console.log(result);
})
</script>
删除数据
<script type="text/javascript" charset="utf-8">
TJ_DB.del('tableName', '`id` == 4', function(result) {
console.log(result);
})
</script>
修改数据
<script type="text/javascript" charset="utf-8">
var data = {
"shopId": 2,
"name": "小王"
};
TJ_DB.edit('tableName', '`name` == "王小丫"', data, function(result) {
console.log(result);
})
</script>
查询数据
<script type="text/javascript" charset="utf-8">
TJ_DB.get('tableName', '(`info` like "说明") && ((`shopId` > 1 || `name` == "王小丫") && `read` == true || `id` <= 5)', '`shopId` desc, `id` asc', function(result) {
console.log(result);
})
</script>
注意事项以及其他说明
- 添加数据时,如果参数是一个对象则添加一条数据。要想批量添加只需传一个对象集数组即可
- 所有条件语句中的字段名需用``引起来
- 查询条件如果传1或true,则查询所有数据
- 目前查询条件支持的运算符有()、&&、||、==、>=、>、<=、<、!=、like,模糊查询时关键字(like)两边必须加上空格
- 排序条件中desc表示降序,asc表示升序。使用逗号分割多个排序条件。越靠前的条件权重越高。如果不传排序条件,会按照indexedCreateTime字段降序输出结果(indexedCreateTime是添加数据时插件自动追加的字段,表示创建该条数据时的时间戳)