Flutter持久化存储之数据库存储(sqflite)详解


当前第2页 返回上一页

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类中实现以下方法。

Future close() async => db.close();

事务

sqflite同时支持事务,通过事务可以将多条原子操作放在一起执行,保证操作要么全部执行完成,要么都不执行。
比如有两条书籍数据必须全部插入书库中才算添加成功,则使用如下方法

 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我们就可以开发更丰富的应用程序,在开发实践中大家遇到任何问题都可以给我们发消息反馈,大家一起交流探讨共同进步。针对一些用户的反馈我们将在下一篇介绍Flutter的代码调试。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。


标签:SQLite

返回前面的内容

相关阅读 >>

sql学习之case when then else end的用法

Sqlite5-使用python来读写数据库

python使用sqlalchemy操作mysql

Sqlite不支持right join的解决办法group by

go语言库系列之dotsql详解

android studio如何获取Sqlite数据并显示到listview上

python 操作Sqlite数据库的示例

c# Sqlite数据库入门使用说明

cc++qt数据库与sqltablemodel组件应用教程

python数据库如何连接Sqlite详解

更多相关阅读请进入《Sqlite》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...