欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flutter數(shù)據(jù)庫(kù)的使用方法

 更新時(shí)間:2021年05月08日 09:34:37   作者:如此風(fēng)景  
這篇文章主要介紹了Flutter數(shù)據(jù)庫(kù)的使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

說(shuō)明

Flutter原生是沒有支持?jǐn)?shù)據(jù)庫(kù)操作的,它使用SQLlit插件來(lái)使應(yīng)用具有使用數(shù)據(jù)庫(kù)的能力。其實(shí)就是Flutter通過(guò)插件來(lái)與原生系統(tǒng)溝通,來(lái)進(jìn)行數(shù)據(jù)庫(kù)操作。

平臺(tái)支持

  • FLutter的SQLite插件支持IOS,安卓,和MacOS平臺(tái)
  • 如果要對(duì)Linux / Windows / DartVM進(jìn)行支持請(qǐng)使用sqflite_common_ffi
  • 不支持web平臺(tái)
  • 數(shù)據(jù)庫(kù)操作在安卓或ios的后臺(tái)執(zhí)行

使用案例

notepad_sqflite 可以在iOS / Android / Windows / linux / Mac上運(yùn)行的簡(jiǎn)單的記事本應(yīng)用

簡(jiǎn)單使用

添加依賴

為了使用 SQLite 數(shù)據(jù)庫(kù),首先需要導(dǎo)入 sqflite 和 path 這兩個(gè) package

  • sqflite 提供了豐富的類和方法,以便你能便捷實(shí)用 SQLite 數(shù)據(jù)庫(kù)。
  • path 提供了大量方法,以便你能正確的定義數(shù)據(jù)庫(kù)在磁盤上的存儲(chǔ)位置。
dependencies:
  sqflite: ^1.3.0
  path:版本號(hào)

使用

導(dǎo)入 sqflite.dart

import 'dart:async';

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

打開數(shù)據(jù)庫(kù)
SQLite數(shù)據(jù)庫(kù)就是文件系統(tǒng)中的文件。如果是相對(duì)路徑,則該路徑是getDatabasesPath()所獲得的路徑,該路徑關(guān)聯(lián)的是Android上的默認(rèn)數(shù)據(jù)庫(kù)目錄和iOS上的documents目錄。

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

許多時(shí)候我們使用數(shù)據(jù)庫(kù)時(shí)不需要手動(dòng)關(guān)閉它,因?yàn)閿?shù)據(jù)庫(kù)會(huì)在程序關(guān)閉時(shí)被關(guān)閉。如果你想自動(dòng)釋放資源,可以使用如下方式:

await db.close();

執(zhí)行原始的SQL查詢

使用getDatabasesPath()獲取數(shù)據(jù)庫(kù)位置

使用 sqflite package 里的 getDatabasesPath 方法并配合 path package里的 join 方法定義數(shù)據(jù)庫(kù)的路徑。使用path包中的join方法是確保各個(gè)平臺(tái)路徑正確性的最佳實(shí)踐。

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

打開數(shù)據(jù)庫(kù)

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

在事務(wù)中向表中插入幾條數(shù)據(jù)

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');
});

刪除表中的一條數(shù)據(jù)

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

修改表中的數(shù)據(jù)

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

查詢表中的數(shù)據(jù)

// 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);

查詢表中存儲(chǔ)數(shù)據(jù)的總條數(shù)

count = Sqflite.firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));

關(guān)閉數(shù)據(jù)庫(kù)

await database.close();

刪除數(shù)據(jù)庫(kù)

await deleteDatabase(path);

使用SQL助手

創(chuàng)建表中的字段及關(guān)聯(lián)類

//字段
final String tableTodo = 'todo';
final String columnId = '_id';
final String columnTitle = 'title';
final String columnDone = 'done';

//對(duì)應(yīng)類
class Todo {
  int id;
  String title;
  bool done;

  //把當(dāng)前類中轉(zhuǎn)換成Map,以供外部使用
  Map<String, Object?> toMap() {
    var map = <String, Object?>{
      columnTitle: title,
      columnDone: done == true ? 1 : 0
    };
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }
  //無(wú)參構(gòu)造
  Todo();
  
  //把map類型的數(shù)據(jù)轉(zhuǎn)換成當(dāng)前類對(duì)象的構(gòu)造函數(shù)。
  Todo.fromMap(Map<String, Object?> map) {
    id = map[columnId];
    title = map[columnTitle];
    done = map[columnDone] == 1;
  }
}

使用上面的類進(jìn)行創(chuàng)建刪除數(shù)據(jù)庫(kù)以及數(shù)據(jù)的增刪改查操作。

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)
                        ''');
    });
  }

  //向表中插入一條數(shù)據(jù),如果已經(jīng)插入過(guò)了,則替換之前的。
  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();
}

=查詢表中的所有數(shù)據(jù)

List<Map<String, Object?>> records = await db.query('my_table');

獲取結(jié)果中的第一條數(shù)據(jù)

Map<String, Object?> mapRead = records.first;

上面查詢結(jié)果的列表中Map為只讀數(shù)據(jù),修改此數(shù)據(jù)會(huì)拋出異常

mapRead['my_column'] = 1;
// Crash... `mapRead` is read-only

創(chuàng)建map副本并修改其中的字段

// 根據(jù)上面的map創(chuàng)建一個(gè)map副本
Map<String, Object?> map = Map<String, Object?>.from(mapRead);
// 在內(nèi)存中修改此副本中存儲(chǔ)的字段值
map['my_column'] = 1;

把查詢出來(lái)的List< map>類型的數(shù)據(jù)轉(zhuǎn)換成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],
    );
  });

批處理

您可以使用批處理來(lái)避免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();

獲取每個(gè)操作的結(jié)果是需要成本的(插入的Id以及更新和刪除的更改數(shù))。如果您不關(guān)心操作的結(jié)果則可以執(zhí)行如下操作關(guān)閉結(jié)果的響應(yīng)

await batch.commit(noResult: true);

事務(wù)中使用批處理

在事務(wù)中進(jìn)行批處理操作,當(dāng)事務(wù)提交后才會(huì)提交批處理。

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();
  
  //  ...
});

批處理異常忽略

默認(rèn)情況下批處理中一旦出現(xiàn)錯(cuò)誤就會(huì)停止(未執(zhí)行的語(yǔ)句則不會(huì)被執(zhí)行了),你可以忽略錯(cuò)誤,以便后續(xù)操作的繼續(xù)執(zhí)行。

await batch.commit(continueOnError: true);

關(guān)于表名和列名

通常情況下我們應(yīng)該避免使用SQLite關(guān)鍵字來(lái)命名表名稱和列名稱。如:

"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"

支持的存儲(chǔ)類型

  • 由于尚未對(duì)值進(jìn)行有效性檢查,因此請(qǐng)避免使用不受支持的類型。參見:
  • 不支持DateTime類型,可將它存儲(chǔ)為int或String
  • 不支持bool類型,可存儲(chǔ)為int類型 0:false,1:true

SQLite類型 dart類型 值范圍
integer int 從-2 ^ 63到2 ^ 63-1
real num
text String
blob Uint8List

參考

sqflile官方地址
flutter對(duì)使用SQLite進(jìn)行數(shù)據(jù)存儲(chǔ)官方介紹文檔

到此這篇關(guān)于Flutter數(shù)據(jù)庫(kù)的使用方法的文章就介紹到這了,更多相關(guān)Flutter數(shù)據(jù)庫(kù)使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Flutter集成高德地圖并添加自定義Maker的實(shí)踐

    Flutter集成高德地圖并添加自定義Maker的實(shí)踐

    本文主要介紹了Flutter集成高德地圖并添加自定義Maker的實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Android自定義仿ios加載彈窗

    Android自定義仿ios加載彈窗

    這篇文章主要為大家詳細(xì)介紹了Android自定義仿ios加載彈窗,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-05-05
  • Android?RecyclerView實(shí)現(xiàn)九宮格效果

    Android?RecyclerView實(shí)現(xiàn)九宮格效果

    這篇文章主要為大家詳細(xì)介紹了Android?RecyclerView實(shí)現(xiàn)九宮格效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • Android開發(fā)自學(xué)筆記(四):APP布局下

    Android開發(fā)自學(xué)筆記(四):APP布局下

    這篇文章主要介紹了Android開發(fā)自學(xué)筆記(四):APP布局下,本文是上一篇的補(bǔ)充,需要的朋友可以參考下
    2015-04-04
  • Android App開發(fā)中創(chuàng)建Fragment組件的教程

    Android App開發(fā)中創(chuàng)建Fragment組件的教程

    這篇文章主要介紹了Android App開發(fā)中創(chuàng)建Fragment的教程,Fragment是用以更靈活地構(gòu)建多屏幕界面的可UI組件,需要的朋友可以參考下
    2016-05-05
  • Android中Window的管理深入講解

    Android中Window的管理深入講解

    這篇文章主要給大家介紹了關(guān)于Android中Window管理的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • Android數(shù)據(jù)加密之Aes加密

    Android數(shù)據(jù)加密之Aes加密

    這篇文章主要為大家詳細(xì)介紹了Android數(shù)據(jù)加密之Aes加密,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • Android中js和原生交互的示例代碼

    Android中js和原生交互的示例代碼

    本篇文章主要介紹了Android中js和原生交互的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-08-08
  • android studio集成極光推送的操作步驟

    android studio集成極光推送的操作步驟

    這篇文章主要介紹了android studio集成極光推送的操作步驟,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • Android中實(shí)現(xiàn)可滑動(dòng)的Tab的3種方式

    Android中實(shí)現(xiàn)可滑動(dòng)的Tab的3種方式

    這篇文章主要介紹了Android中實(shí)現(xiàn)可滑動(dòng)的Tab的3種方式,需要的朋友可以參考下
    2014-02-02

最新評(píng)論