sqflite使用
引入插件
在pubspec.yaml文件中添加path_provider插件,2019年2月18號最新版本為1.1.0:
dependencies:
flutter:
sdk: flutter
#sqflite插件
sqflite: ^1.1.0
執行 flutter packages get 下載插件。
數據庫操作方法介紹
1. 創建數據庫文件和對應的表
// 獲取數據庫文件的存儲路徑
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
//根據數據庫文件路徑和數據庫版本號創建數據庫表
db = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
CREATE TABLE $tableBook (
$columnId INTEGER PRIMARY KEY,
$columnName TEXT,
$columnAuthor TEXT,
$columnPrice REAL,
$columnPublishingHouse TEXT)
''');
});
2. CRUD操作實現
// 插入一條書籍數據
Future<Book> insert(Book book) async {
book.id = await db.insert(tableBook, book.toMap());
return book;
}
// 查找所有書籍信息
Future<List<Book>> queryAll() async {
List<Map> maps = await db.query(tableBook, columns: [
columnId,
columnName,
columnAuthor,
columnPrice,
columnPublishingHouse
]);
if (maps == null || maps.length == 0) {
return null;
}
List<Book> books = [];
for (int i = 0; i < maps.length; i++) {
books.add(Book.fromMap(maps[i]));
}
return books;
}
// 根據ID查找書籍信息
Future<Book> getBook(int id) async {
List<Map> maps = await db.query(tableBook,
columns: [
columnId,
columnName,
columnAuthor,
columnPrice,
columnPublishingHouse
],
where: '$columnId = ?',
whereArgs: [id]);
if (maps.length > 0) {
return Book.fromMap(maps.first);
}
return null;
}
// 根據ID刪除書籍信息
Future<int> delete(int id) async {
return await db.delete(tableBook, where: '$columnId = ?', whereArgs: [id]);
}
// 更新書籍信息
Future<int> update(Book book) async {
return await db.update(tableBook, book.toMap(),
where: '$columnId = ?', whereArgs: [book.id]);
}
3. 關閉數據庫
數據庫對象使用完之后要在適當的時候關閉掉,可在helper類中實現以下方法。
Future close() async => db.close();
github demo代碼地址:https://github.com/xinwii/flutter_sqlite_demo