溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在Android中如何使用Flutter數據庫

發布時間:2022-02-25 14:35:32 來源:億速云 閱讀:491 作者:小新 欄目:開發技術

這篇文章主要介紹了在Android中如何使用Flutter數據庫,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

說明

Flutter原生是沒有支持數據庫操作的,它使用SQLlit插件來使應用具有使用數據庫的能力。其實就是Flutter通過插件來與原生系統溝通,來進行數據庫操作。

平臺支持

  • FLutter的SQLite插件支持IOS,安卓,和MacOS平臺

  • 如果要對Linux / Windows / DartVM進行支持請使用sqflite_common_ffi

  • 不支持web平臺

  • 數據庫操作在安卓或ios的后臺執行

使用案例

notepad_sqflite 可以在iOS / Android / Windows / linux / Mac上運行的簡單的記事本應用

簡單使用

添加依賴

為了使用 SQLite 數據庫,首先需要導入 sqflite 和 path 這兩個 package

  • sqflite 提供了豐富的類和方法,以便你能便捷實用 SQLite 數據庫。

  • path 提供了大量方法,以便你能正確的定義數據庫在磁盤上的存儲位置。

dependencies:
  sqflite: ^1.3.0
  path:版本號

使用

導入 sqflite.dart

import 'dart:async';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

打開數據庫
SQLite數據庫就是文件系統中的文件。如果是相對路徑,則該路徑是getDatabasesPath()所獲得的路徑,該路徑關聯的是Android上的默認數據庫目錄和iOS上的documents目錄。

var db = await openDatabase('my_db.db');

許多時候我們使用數據庫時不需要手動關閉它,因為數據庫會在程序關閉時被關閉。如果你想自動釋放資源,可以使用如下方式:

await db.close();

執行原始的SQL查詢

使用getDatabasesPath()獲取數據庫位置

使用 sqflite package 里的 getDatabasesPath 方法并配合 path package里的 join 方法定義數據庫的路徑。使用path包中的join方法是確保各個平臺路徑正確性的最佳實踐。

var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');

打開數據庫:

Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // 創建數據庫時創建表
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

增:

在事務中向表中插入幾條數據

await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
      ['another name', 12345678, 3.1416]);
  print('inserted2: $id2');
});

刪:

刪除表中的一條數據

count = await database
    .rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);

改:

修改表中的數據

int count = await database.rawUpdate('UPDATE Test SET name = ?, value = ? WHERE name = ?',
    ['updated name', '9876', 'some name']);
print('updated: $count');

查:

查詢表中的數據

// 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類型值范圍
integerint從-2 ^ 63到2 ^ 63-1
realnum
textString
blobUint8List

感謝你能夠認真閱讀完這篇文章,希望小編分享的“在Android中如何使用Flutter數據庫”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女