Flutter中使用sqlite

sqflite使用

引入插件

在pubspec.yaml文件中添加path_provider插件,2019年2月18號最新版本爲1.1.0:git

dependencies:
  flutter:
    sdk: flutter
  #sqflite插件
  sqflite: ^1.1.0
複製代碼

執行 flutter packages get 下載插件。github

數據庫操做方法介紹

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類中實現如下方法。sql

Future close() async => db.close();
複製代碼

github demo代碼地址:github.com/xinwii/flut…

相關文章
相關標籤/搜索