Flutter使用SQLite持久化數(shù)據(jù)

本文從一個(gè)簡單數(shù)據(jù)庫示例來展示flutter使用數(shù)據(jù)庫的簡單的增刪改查方法的基礎(chǔ)知識

Flutter應(yīng)用程序可以通過sqflitepub.dev上可用的插件來利用SQLite數(shù)據(jù)庫 蔚约。本示例演示了sqflite 用于插入提前,讀取澜掩,更新和刪除有關(guān)各種Dog的數(shù)據(jù)的基礎(chǔ)知識牺陶。

如果您不熟悉SQLite和SQL語句仍稀,請?jiān)谕瓿杀臼纠埃殚?SQLite教程以了解基礎(chǔ)知識会钝。

本示例使用以下步驟:

  1. 添加依賴項(xiàng)向臀。
  2. 定義Dog數(shù)據(jù)模型。
  3. 打開數(shù)據(jù)庫架谎。
  4. 創(chuàng)建dogs表炸宵。
  5. 將aDog插入數(shù)據(jù)庫。
  6. 檢索狗列表谷扣。
  7. 更新Dog數(shù)據(jù)庫中的一個(gè)土全。
  8. Dog從數(shù)據(jù)庫中刪除一個(gè)捎琐。

1.添加依賴項(xiàng)

要使用SQLite數(shù)據(jù)庫,需導(dǎo)入sqflitepath軟件包裹匙。

  • sqflite軟件包提供了與SQLite數(shù)據(jù)庫進(jìn)行交互的類和函數(shù)瑞凑。
  • path軟件包提供了一些功能來定義將數(shù)據(jù)庫存儲(chǔ)在磁盤上的位置。
dependencies:
  flutter:
    sdk: flutter
  sqflite: ^1.3.2+2
  path: ^1.7.0

確保將軟件包導(dǎo)入您將要使用的文件中概页。

import 'dart:async';

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

2.定義狗數(shù)據(jù)模型

在創(chuàng)建用于在Dogs上存儲(chǔ)信息的表之前籽御,請花一些時(shí)間來定義需要存儲(chǔ)的數(shù)據(jù)。對于此示例惰匙,定義一個(gè)Dog類技掏,其中包含三段數(shù)據(jù):每條狗的idname项鬼,age哑梳。

class Dog {
  final int id;
  final String name;
  final int age;

  Dog({this.id, this.name, this.age});
}

3.打開數(shù)據(jù)庫

在將數(shù)據(jù)讀取和寫入數(shù)據(jù)庫之前,要先打開與數(shù)據(jù)庫的連接绘盟。這涉及兩個(gè)步驟:

  1. 定義路徑鸠真,使用path包下的getDatabasesPath()組合join獲取數(shù)據(jù)庫文件地址。數(shù)據(jù)庫文件從 龄毡,與組合join從功能path包弧哎。
  2. 使用中使用sqflite包下的openDatabase()功能打開數(shù)據(jù)庫sqflite

注意: 為了使用關(guān)鍵字await稚虎,必須將代碼放在async函數(shù)內(nèi)。應(yīng)該將以下所有表函數(shù)放在內(nèi)void main() async {}偎捎。


final Future<Database> database = openDatabase(
 //獲取數(shù)據(jù)庫對象
  join(await getDatabasesPath(), 'doggie_database.db'),
);

4.創(chuàng)建dogs

接下來蠢终,創(chuàng)建一個(gè)表來存儲(chǔ)有關(guān)各種狗的信息。對于此示例茴她,創(chuàng)建一個(gè)名為的表寻拂,該表dogs定義可以存儲(chǔ)的數(shù)據(jù)。每個(gè)Dog包含一個(gè)id丈牢,nameage祭钉。因此,它們在dogs表中表示為三列己沛。

  1. id是Dart的int慌核,并且被存儲(chǔ)為INTEGERSQLite的數(shù)據(jù)類型。最好使用anid作為表的主鍵來縮短查詢和更新時(shí)間申尼。
  2. name是Dart的String垮卓,并且被存儲(chǔ)為TEXTSQLite的數(shù)據(jù)類型。
  3. age也是Dart的int师幕,并且被存儲(chǔ)為INTEGER 數(shù)據(jù)類型粟按。

有關(guān)可以存儲(chǔ)在SQLite數(shù)據(jù)庫中的可用數(shù)據(jù)類型的更多信息,請參見官方SQLite數(shù)據(jù)類型文檔

final Future<Database> database = openDatabase(
  // Set the path to the database. Note: Using the `join` function from the
  // `path` package is best practice to ensure the path is correctly
  // constructed for each platform.
  join(await getDatabasesPath(), 'doggie_database.db'),
  // When the database is first created, create a table to store dogs.
  onCreate: (db, version) {
    // Run the CREATE TABLE statement on the database.
    return db.execute(
      "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
    );
  },
  // Set the version. This executes the onCreate function and provides a
  // path to perform database upgrades and downgrades.
  version: 1,
);

5.將一只狗插入數(shù)據(jù)庫

現(xiàn)在灭将,您已經(jīng)有了一個(gè)數(shù)據(jù)庫疼鸟,其中包含一個(gè)適用于存儲(chǔ)有關(guān)各種狗的信息的表的表,是時(shí)候讀寫數(shù)據(jù)了庙曙。

首先空镜,將aDog插入dogs表格。這涉及兩個(gè)步驟:

  1. 將轉(zhuǎn)換DogMap
  2. 使用insert()方法將儲(chǔ)存 Mapdogs表格中矾利。
// Update the Dog class to include a `toMap` method.
class Dog {
  final int id;
  final String name;
  final int age;

  Dog({this.id, this.name, this.age});

  // Convert a Dog into a Map. The keys must correspond to the names of the
  // columns in the database.
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
    };
  }
}

// Define a function that inserts dogs into the database
Future<void> insertDog(Dog dog) async {
  // Get a reference to the database.
  final Database db = await database;

  // Insert the Dog into the correct table. You might also specify the
  // `conflictAlgorithm` to use in case the same dog is inserted twice.
  //
  // In this case, replace any previous data.
  await db.insert(
    'dogs',
    dog.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

// Create a Dog and add it to the dogs table.
final fido = Dog(
  id: 0,
  name: 'Fido',
  age: 35,
);

await insertDog(fido);

6.檢索狗列表

現(xiàn)在姑裂,一個(gè)Dog已存儲(chǔ)在數(shù)據(jù)庫中,請?jiān)跀?shù)據(jù)庫中查詢特定的狗或所有狗的列表男旗。這涉及兩個(gè)步驟:

  1. querydogs表運(yùn)行 舶斧。這將返回List<Map>
  2. 將轉(zhuǎn)換List<Map>List<Dog>察皇。
// A method that retrieves all the dogs from the dogs table.
Future<List<Dog>> dogs() async {
  // Get a reference to the database.
  final Database db = await database;

  // Query the table for all The Dogs.
  final List<Map<String, dynamic>> maps = await db.query('dogs');

  // Convert the List<Map<String, dynamic> into a List<Dog>.
  return List.generate(maps.length, (i) {
    return Dog(
      id: maps[i]['id'],
      name: maps[i]['name'],
      age: maps[i]['age'],
    );
  });
}

// Now, use the method above to retrieve all the dogs.
print(await dogs()); // Prints a list that include Fido.

7.更新Dog數(shù)據(jù)庫中的

將信息插入數(shù)據(jù)庫后茴厉,您可能希望稍后再更新該信息∈踩伲可以使用庫中的update() 方法執(zhí)行此操作sqflite矾缓。

這涉及兩個(gè)步驟:

  1. 將狗轉(zhuǎn)換成地圖。
  2. 使用where子句以確保更新正確的Dog稻爬。
Future<void> updateDog(Dog dog) async {
  // Get a reference to the database.
  final db = await database;

  // Update the given Dog.
  await db.update(
    'dogs',
    dog.toMap(),
    // Ensure that the Dog has a matching id.
    where: "id = ?",
    // Pass the Dog's id as a whereArg to prevent SQL injection.
    whereArgs: [dog.id],
  );
}

// Update Fido's age.
await updateDog(Dog(
  id: 0,
  name: 'Fido',
  age: 42,
));

// Print the updated results.
print(await dogs()); // Prints Fido with age 42.

警告: 始終用于whereArgs將參數(shù)傳遞給where語句嗜闻。這有助于防止SQL注入攻擊。

請勿使用字符串插值桅锄,例如where: "id = ${dog.id}"琉雳!

8.Dog從數(shù)據(jù)庫中刪除

除了插入和更新有關(guān)Dogs的信息外,您還可以從數(shù)據(jù)庫中刪除Dogs友瘤。要?jiǎng)h除數(shù)據(jù)翠肘,請使用庫中的delete()方法sqflite

在本節(jié)中辫秧,創(chuàng)建一個(gè)接受ID的函數(shù)束倍,并從數(shù)據(jù)庫中刪除具有匹配ID的狗。要使此工作有效盟戏,您必須提供一個(gè)where 子句以限制要?jiǎng)h除的記錄绪妹。

Future<void> deleteDog(int id) async {
  // Get a reference to the database.
  final db = await database;

  // Remove the Dog from the Database.
  await db.delete(
    'dogs',
    // Use a `where` clause to delete a specific dog.
    where: "id = ?",
    // Pass the Dog's id as a whereArg to prevent SQL injection.
    whereArgs: [id],
  );
}

9.運(yùn)行示例:

  1. 創(chuàng)建一個(gè)新的Flutter項(xiàng)目。
  2. sqflitepath軟件包添加到您的中pubspec.yaml柿究。
  3. 將以下代碼粘貼到名為的新文件中lib/db_test.dart喂急。
  4. 使用運(yùn)行代碼flutter run lib/db_test.dart
import 'dart:async';

import 'package:flutter/widgets.dart';

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

void main() async {
  // Avoid errors caused by flutter upgrade.
  // Importing 'package:flutter/widgets.dart' is required.
  WidgetsFlutterBinding.ensureInitialized();
  // Open the database and store the reference.
  final Future<Database> database = openDatabase(
    // Set the path to the database. Note: Using the `join` function from the
    // `path` package is best practice to ensure the path is correctly
    // constructed for each platform.
    join(await getDatabasesPath(), 'doggie_database.db'),
    // When the database is first created, create a table to store dogs.
    onCreate: (db, version) {
      return db.execute(
        "CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
      );
    },
    // Set the version. This executes the onCreate function and provides a
    // path to perform database upgrades and downgrades.
    version: 1,
  );

  Future<void> insertDog(Dog dog) async {
    // Get a reference to the database.
    final Database db = await database;

    // Insert the Dog into the correct table. Also specify the
    // `conflictAlgorithm`. In this case, if the same dog is inserted
    // multiple times, it replaces the previous data.
    await db.insert(
      'dogs',
      dog.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<List<Dog>> dogs() async {
    // Get a reference to the database.
    final Database db = await database;

    // Query the table for all The Dogs.
    final List<Map<String, dynamic>> maps = await db.query('dogs');

    // Convert the List<Map<String, dynamic> into a List<Dog>.
    return List.generate(maps.length, (i) {
      return Dog(
        id: maps[i]['id'],
        name: maps[i]['name'],
        age: maps[i]['age'],
      );
    });
  }

  Future<void> updateDog(Dog dog) async {
    // Get a reference to the database.
    final db = await database;

    // Update the given Dog.
    await db.update(
      'dogs',
      dog.toMap(),
      // Ensure that the Dog has a matching id.
      where: "id = ?",
      // Pass the Dog's id as a whereArg to prevent SQL injection.
      whereArgs: [dog.id],
    );
  }

  Future<void> deleteDog(int id) async {
    // Get a reference to the database.
    final db = await database;

    // Remove the Dog from the database.
    await db.delete(
      'dogs',
      // Use a `where` clause to delete a specific dog.
      where: "id = ?",
      // Pass the Dog's id as a whereArg to prevent SQL injection.
      whereArgs: [id],
    );
  }

  var fido = Dog(
    id: 0,
    name: 'Fido',
    age: 35,
  );

  // Insert a dog into the database.
  await insertDog(fido);

  // Print the list of dogs (only Fido for now).
  print(await dogs());

  // Update Fido's age and save it to the database.
  fido = Dog(
    id: fido.id,
    name: fido.name,
    age: fido.age + 7,
  );
  await updateDog(fido);

  // Print Fido's updated information.
  print(await dogs());

  // Delete Fido from the database.
  await deleteDog(fido.id);

  // Print the list of dogs (empty).
  print(await dogs());
}

class Dog {
  final int id;
  final String name;
  final int age;

  Dog({this.id, this.name, this.age});

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
    };
  }

  // Implement toString to make it easier to see information about
  // each dog when using the print statement.
  @override
  String toString() {
    return 'Dog{id: $id, name: $name, age: $age}';
  }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末笛求,一起剝皮案震驚了整個(gè)濱河市廊移,隨后出現(xiàn)的幾起案子糕簿,更是在濱河造成了極大的恐慌,老刑警劉巖狡孔,帶你破解...
    沈念sama閱讀 211,123評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件懂诗,死亡現(xiàn)場離奇詭異,居然都是意外死亡苗膝,警方通過查閱死者的電腦和手機(jī)殃恒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評論 2 384
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來辱揭,“玉大人离唐,你說我怎么就攤上這事∥是裕” “怎么了亥鬓?”我有些...
    開封第一講書人閱讀 156,723評論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長域庇。 經(jīng)常有香客問我嵌戈,道長,這世上最難降的妖魔是什么听皿? 我笑而不...
    開封第一講書人閱讀 56,357評論 1 283
  • 正文 為了忘掉前任熟呛,我火速辦了婚禮,結(jié)果婚禮上尉姨,老公的妹妹穿的比我還像新娘庵朝。我一直安慰自己,他們只是感情好又厉,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評論 5 384
  • 文/花漫 我一把揭開白布偿短。 她就那樣靜靜地躺著,像睡著了一般馋没。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上降传,一...
    開封第一講書人閱讀 49,760評論 1 289
  • 那天篷朵,我揣著相機(jī)與錄音,去河邊找鬼婆排。 笑死声旺,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的段只。 我是一名探鬼主播腮猖,決...
    沈念sama閱讀 38,904評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼赞枕!你這毒婦竟也來了澈缺?” 一聲冷哼從身側(cè)響起坪创,我...
    開封第一講書人閱讀 37,672評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎姐赡,沒想到半個(gè)月后莱预,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,118評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡项滑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評論 2 325
  • 正文 我和宋清朗相戀三年依沮,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片枪狂。...
    茶點(diǎn)故事閱讀 38,599評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡危喉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出州疾,到底是詐尸還是另有隱情辜限,我是刑警寧澤,帶...
    沈念sama閱讀 34,264評論 4 328
  • 正文 年R本政府宣布孝治,位于F島的核電站列粪,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏谈飒。R本人自食惡果不足惜岂座,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望杭措。 院中可真熱鬧费什,春花似錦、人聲如沸手素。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽泉懦。三九已至稿黍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間崩哩,已是汗流浹背巡球。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留邓嘹,地道東北人酣栈。 一個(gè)月前我還...
    沈念sama閱讀 46,286評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像汹押,于是被迫代替她去往敵國和親矿筝。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評論 2 348

推薦閱讀更多精彩內(nèi)容