查询表中的数据
// Get the records List<Map> list = await database.rawQuery('SELECT * FROM Test'); List<Map> expectedList = [ {'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789}, {'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416} ]; print(list); print(expectedList);
查询表中存储数据的总条数
count = Sqflite.firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
关闭数据库
await database.close();
删除数据库
await deleteDatabase(path);
使用SQL助手
创建表中的字段及关联类
//字段 final String tableTodo = 'todo'; final String columnId = '_id'; final String columnTitle = 'title'; final String columnDone = 'done'; //对应类 class Todo { int id; String title; bool done; //把当前类中转换成Map,以供外部使用 Map<String, Object?> toMap() { var map = <String, Object?>{ columnTitle: title, columnDone: done == true ? 1 : 0 }; if (id != null) { map[columnId] = id; } return map; } //无参构造 Todo(); //把map类型的数据转换成当前类对象的构造函数。 Todo.fromMap(Map<String, Object?> map) { id = map[columnId]; title = map[columnTitle]; done = map[columnDone] == 1; } }
使用上面的类进行创建删除数据库以及数据的增删改查操作。
class TodoProvider { Database db; Future open(String path) async { db = await openDatabase(path, version: 1, onCreate: (Database db, int version) async { await db.execute(''' create table $tableTodo ( $columnId integer primary key autoincrement, $columnTitle text not null, $columnDone integer not null) '''); }); } //向表中插入一条数据,如果已经插入过了,则替换之前的。 Future<Todo> insert(Todo todo) async { todo.id = await db.insert(tableTodo, todo.toMap(),conflictAlgorithm: ConflictAlgorithm.replace,); return todo; } Future<Todo> getTodo(int id) async { List<Map> maps = await db.query(tableTodo, columns: [columnId, columnDone, columnTitle], where: '$columnId = ?', whereArgs: [id]); if (maps.length > 0) { return Todo.fromMap(maps.first); } return null; } Future<int> delete(int id) async { return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]); } Future<int> update(Todo todo) async { return await db.update(tableTodo, todo.toMap(), where: '$columnId = ?', whereArgs: [todo.id]); } Future close() async => db.close(); }
=查询表中的所有数据
List<Map<String, Object?>> records = await db.query('my_table');
获取结果中的第一条数据
Map<String, Object?> mapRead = records.first;
上面查询结果的列表中Map为只读数据,修改此数据会抛出异常
mapRead['my_column'] = 1; // Crash... `mapRead` is read-only
创建map副本并修改其中的字段
// 根据上面的map创建一个map副本 Map<String, Object?> map = Map<String, Object?>.from(mapRead); // 在内存中修改此副本中存储的字段值 map['my_column'] = 1;
把查询出来的List< map>类型的数据转换成List< Todo>类型,这样我们就可以痛快的使用啦。
// Convert the List<Map<String, dynamic> into a List<Todo>. return List.generate(maps.length, (i) { return Todo( id: maps[i][columnId], title: maps[i][columnTitle], done: maps[i][columnDown], ); });
批处理
您可以使用批处理来避免dart与原生之间频繁的交互。
batch = db.batch(); batch.insert('Test', {'name': 'item'}); batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']); batch.delete('Test', where: 'name = ?', whereArgs: ['item']); results = await batch.commit();
获取每个操作的结果是需要成本的(插入的Id以及更新和删除的更改数)。如果您不关心操作的结果则可以执行如下操作关闭结果的响应
await batch.commit(noResult: true);
事务中使用批处理
在事务中进行批处理操作,当事务提交后才会提交批处理。
await database.transaction((txn) async { var batch = txn.batch(); // ... // commit but the actual commit will happen when the transaction is committed // however the data is available in this transaction await batch.commit(); // ... });
批处理异常忽略
默认情况下批处理中一旦出现错误就会停止(未执行的语句则不会被执行了),你可以忽略错误,以便后续操作的继续执行。
await batch.commit(continueOnError: true);
关于表名和列名
通常情况下我们应该避免使用SQLite关键字来命名表名称和列名称。如:
"add","all","alter","and","as","autoincrement","between","case","check","collate",
"commit","constraint","create","default","deferrable","delete","distinct","drop",
"else","escape","except","exists","foreign","from","group","having","if","in","index",
"insert","intersect","into","is","isnull","join","limit","not","notnull","null","on",
"or","order","primary","references","select","set","table","then","to","transaction",
"union","unique","update","using","values","when","where"
支持的存储类型
- 由于尚未对值进行有效性检查,因此请避免使用不受支持的类型。参见:
- 不支持DateTime类型,可将它存储为int或String
- 不支持bool类型,可存储为int类型 0:false,1:true
SQLite类型 | dart类型 | 值范围 |
---|---|---|
integer | int | 从-2 ^ 63到2 ^ 63-1 |
real | num | |
text | String | |
blob | Uint8List |
参考
sqflile官方地址
flutter对使用SQLite进行数据存储官方介绍文档
到此这篇关于Flutter数据库的使用方法的文章就介绍到这了,更多相关Flutter数据库使用内容请搜索
标签:SQLite
相关阅读 >>
androidstudio数据存储建立Sqlite数据库实现增删查改
更多相关阅读请进入《Sqlite》频道 >>

数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。