FlutterNoSql数据库Sembast初探
什么是Sembast?
Sembast是可⽤于DartVM和Fluutter的NoSql数据库。Sembast是基于⽂档的数据库,并且⽀持加密。
对于NoSql数据库的使⽤者来说,最⼤的吸引⼒莫过于易扩展了。相对于关系型数据库,开发者不必疲于维护数据字段或者表结构升级等繁琐的⼯作。尤其对于Flutter来说,作为⼀个客户端技术热更新技术是⼀直被使⽤者诟病的⽅⾯,所以发版前保证更新后的应⽤能正常使⽤是⼀个⾮常关键的⼯作,这对开发和测试团队带来了不⼩的挑战。⽐如我们常⽤的SqlLite数据库,⼀旦客户端升级过后,数据库升级带来不可逆的错误,可能导致⽤户必须卸载重装才能修复,这导致涉及数据库开发的功能测试⼀定会慎之⼜慎。
今天这篇⽂章是对NoSql数据库Sembast的使⽤做⼀个初步的探索。
Sembast特性
Yet another NoSQL persistent store databa solution for single process io applications. The whole document bad databa resides in a single file and is loaded in memory when opened. Changes are appended right away to the file and the file is automatically compacted when needed.
Works on Dart VM and Flutter (no plugin needed, 100% Dart so works on all platforms -
MacOS/Android/iOS/Linux/Windows). Inspired from IndexedDB, DataStore, WebSql, NeDB,
Supports encryption using ur-defined codec.
Pure dart single file IO VM/Flutter storage supported.
Web support (including Flutter Web) through mbast_web.
Can work on top of sqflite through mbast_sqflite.
这⾥引⽤官⽅⽂档介绍下Sembast特性
1. 数据库的加载⽅式:基于⽂档的单⽂件存储模式,打开时加载到内存,更改时会⽴即刷新到⽂件中,并且在必要时⾃动压缩⽂件。
2. 使⽤平台:适⽤于DartVM 和 Flutter,是使⽤纯Dart编写的⽆需插件的数据库,所以适⽤于Flutter全平台。
3. ⽀持使⽤⾃定义编解码器进⾏加密
4. 通过 mbast_web 扩展⽀持 Web(包括 Flutter Web)
王昌龄边塞诗5. 可以通过 mbast_sqflite 扩展在 sqflite 上⼯作
官⽅还提供了开源项⽬和在线Demo⽅便开发者预览效果健康证明
开源项⽬地址:
有动物的诗句在线Demo预览:
数据库使⽤
初始化数据库,官⽅⽰例⾥使⽤了 path_provider 扩展包来实现获取应⽤级⽬录。
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:mbast/mbast_io.dart';摩羯座女生脾气
.
..
// get the application documents directory
草莓冰淇淋var dir = await getApplicationDocumentsDirectory();
// make sure it exists
ate(recursive: true);
// build the databa path
var dbPath = join(dir.path, 'my_databa.db');明季北略
日本礼仪// open the databa
var db = await databaFactoryIo.openDataba(dbPath);
数据库升级,使⽤数据库初始化版本变化时的回调来升级数据库内容
// Our shop store sample data
var store = intMapStoreFactory.store('shop');
var db = await factory.openDataba(path, version: 1,
onVersionChanged: (db, oldVersion, newVersion) async {
// If the db does not exist, create some data
if (oldVersion == 0) {
await store.add(db, {'name': 'Lamp', 'price': 10});
await store.add(db, {'name': 'Chair', 'price': 15});
}
});关于读书的名言警句
数据库读写
1. 获取存储对象
/
/ dynamically typed store
var store = StoreRef.main();
2. 插⼊数据
// Easy to put/get simple values or map
// A key can be of type int or String and the value can be anything as long as it can // be properly JSON encoded/decoded
// 插⼊String类型的记录
d('title').put(db, 'Simple application');
// 插⼊int类型的记录
d('version').put(db, 10);
// 插⼊Map类型的记录
d('ttings').put(db, {'offline': true});
3. 读取数据
var title = d('title').get(db) as String;
var version = d('version').get(db) as int;
var ttings = d('ttings').get(db) as Map;
4. 删除记录
d('version').delete(db);