Flutter持久化存儲之?dāng)?shù)據(jù)庫存儲(sqflite)詳解
前言
數(shù)據(jù)庫存儲是我們常用的存儲方式之一,對大批量數(shù)據(jù)有增、刪、改、查操作需求時,我們就會想到使用數(shù)據(jù)庫,F(xiàn)lutter中提供了一個sqflite插件供我們用于大量數(shù)據(jù)執(zhí)行CRUD操作。本篇我們就來一起學(xué)習(xí)sqflite的使用。
sqflite是一款輕量級的關(guān)系型數(shù)據(jù)庫,類似SQLite。
在Flutter平臺我們使用sqflite庫來同時支持Android 和iOS。
sqflite使用
引入插件
在pubspec.yaml文件中添加path_provider插件,最新版本為1.0.0,如下:
dependencies: flutter: sdk: flutter #sqflite插件 sqflite: 1.0.0
然后命令行執(zhí)行flutter packages get即可將插件下載到本地。
數(shù)據(jù)庫操作方法介紹
1. 插入操作
插入數(shù)據(jù)操作有兩個方法:
Future<int> rawInsert(String sql, [List<dynamic> arguments]);
Future<int> insert(String table, Map<String, dynamic> values,
{String nullColumnHack, ConflictAlgorithm conflictAlgorithm});
rawInsert方法第一個參數(shù)為一條插入sql語句,可以使用?作為占位符,通過第二個參數(shù)填充數(shù)據(jù)。
insert方法第一個參數(shù)為操作的表名,第二個參數(shù)map中是想要添加的字段名和對應(yīng)字段值。
2. 查詢操作
查詢操作同樣實現(xiàn)了兩個方法:
Future<List<Map<String, dynamic>>> query(String table,
{bool distinct,
List<String> columns,
String where,
List<dynamic> whereArgs,
String groupBy,
String having,
String orderBy,
int limit,
int offset});
Future<List<Map<String, dynamic>>> rawQuery(String sql,
[List<dynamic> arguments]);
query方法第一個參數(shù)為操作的表名,后邊的可選參數(shù)依次表示是否去重、查詢字段、WHERE子句(可使用?作為占位符)、WHERE子句占位符參數(shù)值、GROUP BY子句、HAVING子句、ORDER BY子句、查詢的條數(shù)、查詢的偏移位等。
rawQuery方法第一個參數(shù)為一條查詢sql語句,可以使用?作為占位符,通過第二個參數(shù)填充數(shù)據(jù)。
3. 修改操作
修改操作同樣實現(xiàn)了兩個方法:
Future<int> rawUpdate(String sql, [List<dynamic> arguments]);
Future<int> update(String table, Map<String, dynamic> values,
{String where,
List<dynamic> whereArgs,
ConflictAlgorithm conflictAlgorithm});
rawUpdate方法第一個參數(shù)為一條更新sql語句,可以使用?作為占位符,通過第二個參數(shù)填充數(shù)據(jù)。
update方法第一個參數(shù)為操作的表名,第二個參數(shù)為修改的字段和對應(yīng)值,后邊的可選參數(shù)依次表示W(wǎng)HERE子句(可使用?作為占位符)、WHERE子句占位符參數(shù)值、發(fā)生沖突時的操作算法(包括回滾、終止、忽略等等)。
4. 刪除操作
修改操作同樣實現(xiàn)了兩個方法:
Future<int> rawDelete(String sql, [List<dynamic> arguments]);
Future<int> delete(String table, {String where, List<dynamic> whereArgs});
rawDelete方法第一個參數(shù)為一條刪除sql語句,可以使用?作為占位符,通過第二個參數(shù)填充數(shù)據(jù)。
delete方法第一個參數(shù)為操作的表名,后邊的可選參數(shù)依次表示W(wǎng)HERE子句(可使用?作為占位符)、WHERE子句占位符參數(shù)值。
舉個栗子
我們以圖書管理系統(tǒng)來舉例。
首先,我們創(chuàng)建一個書籍類,包括書籍ID、書名、作者、價格、出版社等信息。
final String tableBook = 'book';
final String columnId = '_id';
final String columnName = 'name';
final String columnAuthor = 'author';
final String columnPrice = 'price';
final String columnPublishingHouse = 'publishingHouse';
class Book {
int id;
String name;
String author;
double price;
String publishingHouse;
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
columnName: name,
columnAuthor: author,
columnPrice: price,
columnPublishingHouse: publishingHouse
};
if (id != null) {
map[columnId] = id;
}
return map;
}
Book();
Book.fromMap(Map<String, dynamic> map) {
id = map[columnId];
name = map[columnName];
author = map[columnAuthor];
price = map[columnPrice];
publishingHouse = map[columnPublishingHouse];
}
}
其次,我們開始實現(xiàn)數(shù)據(jù)庫相關(guān)操作:
1. 創(chuàng)建數(shù)據(jù)庫文件和對應(yīng)的表
// 獲取數(shù)據(jù)庫文件的存儲路徑
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
//根據(jù)數(shù)據(jù)庫文件路徑和數(shù)據(jù)庫版本號創(chuàng)建數(shù)據(jù)庫表
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操作實現(xiàn)
// 插入一條書籍?dāng)?shù)據(jù)
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;
}
// 根據(jù)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;
}
// 根據(jù)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. 關(guān)閉數(shù)據(jù)庫
數(shù)據(jù)庫對象使用完之后要在適當(dāng)?shù)臅r候關(guān)閉掉,可在helper類中實現(xiàn)以下方法。
Future close() async => db.close();
事務(wù)
sqflite同時支持事務(wù),通過事務(wù)可以將多條原子操作放在一起執(zhí)行,保證操作要么全部執(zhí)行完成,要么都不執(zhí)行。
比如有兩條書籍?dāng)?shù)據(jù)必須全部插入書庫中才算添加成功,則使用如下方法
Future<bool> insertTwoBook(Book book1, Book book2) async {
return await db.transaction((Transaction txn) async {
book1.id = await db.insert(tableBook, book1.toMap());
book2.id = await db.insert(tableBook, book2.toMap());
print('book1.id = ${book1.id}, book2.id = ${book2.id}');
return book1.id != null && book2.id != null;
});
}
寫在最后
以上介紹了sqflite中我們常用的幾個操作,有了sqflite我們就可以開發(fā)更豐富的應(yīng)用程序,在開發(fā)實踐中大家遇到任何問題都可以給我們發(fā)消息反饋,大家一起交流探討共同進(jìn)步。針對一些用戶的反饋我們將在下一篇介紹Flutter的代碼調(diào)試。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
sweet alert dialog 在android studio應(yīng)用問題說明詳解
這篇文章主要介紹了sweet alert dialog 在android studio應(yīng)用問題說明詳解的相關(guān)資料,本文圖文并茂介紹的非常詳細(xì),具有參考借鑒價值,需要的朋友可以參考下2016-09-09
Android 官推 kotlin-first 的圖片加載庫——Coil的使用入門
這篇文章主要介紹了Android 官推 kotlin-first 的圖片加載庫——Coil的使用入門,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-04-04
Android數(shù)據(jù)共享 sharedPreferences 的使用方法
這篇文章主要介紹了Android數(shù)據(jù)共享 sharedPreferences 的使用方法的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解使用sharedpreferences,需要的朋友可以參考下2017-10-10
Android開發(fā)筆記之Android中數(shù)據(jù)的存儲方式(一)
這篇文章主要介紹了Android開發(fā)筆記之Android中數(shù)據(jù)的存儲方式(一) 的相關(guān)資料,需要的朋友可以參考下2016-01-01
Android 通過webservice上傳多張圖片到指定服務(wù)器詳解
這篇文章主要介紹了Android 通過webservice上傳多張圖片到指定服務(wù)器詳解的相關(guān)資料,需要的朋友可以參考下2017-02-02
activitygroup 切換動畫效果如何實現(xiàn)
本文將詳細(xì)介紹activitygroup 切換動畫效果實現(xiàn)過程,需要聊解的朋友可以參考下2012-12-12
Android系統(tǒng)view與SurfaceView的基本使用及區(qū)別分析
這篇文章主要為大家介紹了Android系統(tǒng)view與SurfaceView基本使用的案例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
Android 通過API獲取數(shù)據(jù)庫中的圖片文件方式
這篇文章主要介紹了Android 通過API獲取數(shù)據(jù)庫中的圖片文件方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03

