Flutter开发笔记 —— sqflite插件数据库应用
前言
今天在观阅掘金大佬文章的时候,了解到了该 sqflite 插件,结合官网教程和自己实践,由此总结出该文,希望对大家的学习有帮助!
插件详情
Flutter的 SQLite 插件。支持 iOS、Android 和 MacOS。
- 支持事务和batch模式
- 打开时自动进行版本管理
- 插入/查询/更新/删除查询的助手
- iOS 和 Android 上的数据库操作在后台线程中执行
插件地址: https://pub.dev/packages/sqflite
本文使用插件版本为最新版本:2.3.0
基础介绍
数据表创建
- openDatabase() 连接数据库
- deleteDatabase() 删除数据库
openDataBase方法 可选参为db文件地址、版本号、相关回调
案例速览
late Database db;
final database = "book.db";
final table = "book";/** @author Marinda* @date 2023/12/13 15:53* @description 连接数据库*/
connection() async{//获取var databasePath = await getDatabasesPath();String path = p.join(databasePath,database);//删除数据库await deleteDatabase(path);print('当前地址:${path}');if(File(path).existsSync()){db = await openDatabase(path);}else{db = await openDatabase(path,version: 1,onCreate: (database,version) async{database.execute("CREATE TABLE `${table}` (id integer primary key autoincrement,name text not null,price REAL ,author TEXT NOT NULL,description TEXT)");});}
}
语句介绍
CURD方法介绍
- 使用SQL语句的CURD前缀带raw (例如rawInsert)
- 官方封装好的CURD语句不带raw(例如insert) ->全文使用该方法
语法速览
//前者
Future<int> rawInsert(String sql, [List<Object?>? arguments]);
//后者
Future<int> insert(String table, Map<String, Object?> values,{String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm});
接下来看几个简单的CURD快速了解写法
insert(插入)
Future<int> insert() async{Map<String,dynamic> args = {"id": 1,"name": "张飞","description": "猛将"};//返回id table为表名return await db.insert(table,args);
}
delete(删除)
Future<int> delete(int id) async{return await db.delete(table,where: "id = ?",whereArgs: [id]);
}
update(修改)
Future<int> update() async{Map<String,dynamic> args = {"id": 1,"name": "吕布","description": "天下无双"};return await db.update(table, args,where: "id = ?",whereArgs: [args["id"]]);
}
select(查询)
/** @author Marinda* @date 2023/12/13 16:11* @description 通过id查询*/
Future<Map<String,dynamic>?> selectById(int id) async{var list = await db.query(table,where: "id = ?",whereArgs: [id]);if(list.isNotEmpty){return list.first;}return null;
}
现在我们对sqflite插件的基础使用有一个初步的了解了,接下来围绕一个书本表案例做实战
实战应用
- 定义Book书表作为实体类
- 定义DBBookProvider类处理数据库表
book.dart
/*** @author Marinda* @date 2023/12/13 15:42* @description 书籍信息*/
class Book {int? _id;String? _name;double? _price;String? _author;String? _description;Book({int? id,String? name,double? price,String? author,String? description}) {if (id != null) {this._id = id;}if (name != null) {this._name = name;}if (price != null) {this._price = price;}if (author != null) {this._author = author;}if (description != null) {this._description = description;}}int? get id => _id;set id(int? id) => _id = id;String? get name => _name;set name(String? name) => _name = name;double? get price => _price;set price(double? price) => _price = price;String? get author => _author;set author(String? author) => _author = author;String? get description => _description;set description(String? description) => _description = description;Book.fromJson(Map<String, dynamic> json) {_id = json['id'];_name = json['name'];_price = json['price'];_author = json['author'];_description = json['description'];}Map<String, dynamic> toJson() {final Map<String, dynamic> data = new Map<String, dynamic>();data['id'] = this._id;data['name'] = this._name;data['price'] = this._price;data['author'] = this._author;data['description'] = this._description;return data;}
}
db_book_provider.dart
/*** @author Marinda* @date 2023/12/13 15:43* @description 书籍数据库适配器*/class DBBookProvider{late Database db;final database = "book.db";final table = "book";static DBBookProvider? _instance;static DBBookProvider instance = getInstance();DBBookProvider._();factory DBBookProvider(){return instance;}static getInstance(){if(_instance == null){_instance = DBBookProvider._();}return _instance ?? DBBookProvider._();}/** @author Marinda* @date 2023/12/13 15:53* @description 连接数据库*/connection() async{var databasePath = await getDatabasesPath();String path = p.join(databasePath,database);// await deleteDatabase(path);print('当前地址:${path}');if(File(path).existsSync()){db = await openDatabase(path);}else{db = await openDatabase(path,version: 1,onCreate: (database,version) async{database.execute("CREATE TABLE `${table}` (id integer primary key autoincrement,name text not null,price REAL ,author TEXT NOT NULL,description TEXT)");});}}/** @author Marinda* @date 2023/12/13 16:01* @description 关闭数据库*/close() async{await db.close();}/** @author Marinda* @date 2023/12/13 16:02* @description 插入*/Future<Book> insert(Book book) async{int id = await db.insert(table,book.toJson());book.id = id;return book;}/** @author Marinda* @date 2023/12/13 16:08* @description 删除id*/Future<int> delete(int id) async{return await db.delete(table,where: "id = ?",whereArgs: [id]);}/** @author Marinda* @date 2023/12/13 16:11* @description 通过id查询*/Future<Book?> selectById(int id) async{var list = await db.query(table,where: "id = ?",whereArgs: [id]);if(list.isNotEmpty){return Book.fromJson(list.first);}return null;}/** @author Marinda* @date 2023/12/13 16:13* @description 获取所有书籍列表*/Future<List<Book>> queryList() async{svar result = await db.query(table);return result.map((e) => Book.fromJson(e)).toList();}/** @author Marinda* @date 2023/12/13 16:15* @description 修改书籍信息*/Future<int> update(Book book) async{return await db.update(table, book.toJson(),where: "id = ?",whereArgs: [book.id]);}}
实例化调用
initDatabase() async{DBBookProvider dbBookProvider = DBBookProvider.instance;//连接await dbBookProvider.connection();Book book = Book(name: "斗破苍穹",author: "天蚕土豆",price: 88.00,description: "一本不错的小说");//插入Book element = await dbBookProvider.insert(book);print('element : ${element.toJson()}');//删除for(var id in result){await dbBookProvider.delete(id);}Book newBook = Book.fromJson(book.toJson());newBook.id = 1;newBook.author = "天蚕土豆";//修改await dbBookProvider.update(newBook);//查询全部var list = await dbBookProvider.queryList();print("当前列表: ${list.map((e) => e.toJson()).toList()}");
}
事务&batch
单独拉出来讲讲的原因是我在应用中踩了个坑
事务和batch是什么这个大家如果不了解的话自行百度一下,下文带大家简单看看案例
/** @author Marinda* @date 2023/12/13 16:17* @description 批量插入全部书籍列表*/
insertAll(List<Book> bookList) async{List resultList = [];await db.transaction((txn) async{Batch batch = txn.batch();for(var book in bookList){batch.insert(table,book.toJson());}//返回全部结果并且不跳过错误!resultList = await batch.commit(noResult: false,continueOnError: false);print('resultList: ${resultList}');});await close();return resultList;
}
注:在该案例中配合事务 batch.commit方法中如果continueOnError为false时 出现异常则会中止,导致前面插入回推。
注:在该insertAll()方法 或其他涉及事务的方法,都要执行完毕后主动调用close() 断开本次连接。否则会导致 Error Domain=FMDatabase Code=5 “database is locked”
如果已经出现 Error Domain=FMDatabase Code=5 “database is locked” 错误,请删除该数据库文件,重新生成。
结束语
感谢你的观看,希望对大家学习有帮助,有不对的地方欢迎指正!
相关文章:
Flutter开发笔记 —— sqflite插件数据库应用
前言 今天在观阅掘金大佬文章的时候,了解到了该 sqflite 插件,结合官网教程和自己实践,由此总结出该文,希望对大家的学习有帮助! 插件详情 Flutter的 SQLite 插件。支持 iOS、Android 和 MacOS。 支持事务和batch模式…...
OxLint 发布了,Eslint 何去何从?
由于最近的rust在前端领域的崛起,基于rust的前端生态链遭到rust底层重构,最近又爆出OxLint,是一款基于Rust的linter工具Oxlint在国外前端圈引起热烈讨论,很多大佬给出了高度评价;你或许不知道OxLint,相比ES…...
第一次使用ThreadPoolExecutor处理业务
通过对业务逻辑的分析,进行编码,先把第一条sql查出来的数据进行分组,然后分别使用不同的线程去查询数据返回,并添加到原来的数据中。 总感觉哪里写的不对,但是同事们都没用过这个,请大家指教一下ÿ…...
Sharding-Jdbc(6):Sharding-Jdbc日志分析
1 修改配置 将配置文件中的开启分片日志从false改为true Sharding-JDBC中的路由结果是通过分片字段和分片方法来确定的,如果查询条件中有 id 字段的情况还好,查询将会落到某个具体的分片;如果查询没有分片的字段,会向所有的db或者是表都会查…...
centos安装了curl却报 -bash: curl: command not found
前因 我服务器上想用curl下载docker-compress,发现没有curl命令,就去下载安装,安装完成之后,报-bash: curl: command not found 解决方法 [rootcentos ~]# rpm -e --nodeps curl warning: file /usr/bin/curl: remove failed: …...
Re58:读论文 REALM: Retrieval-Augmented Language Model Pre-Training
诸神缄默不语-个人CSDN博文目录 诸神缄默不语的论文阅读笔记和分类 论文名称:REALM: Retrieval-Augmented Language Model Pre-Training 模型名称:Retrieval-Augmented Language Model pre-training (REALM) 本文是2020年ICML论文,作者来自…...
java的json解析
import com.alibaba.fastjson.*; public class JsonParser { public static void main(String[] args) { String jsonStr "{\"name\":\"John\", \"age\":30}"; // JSON字符串示例 // 将JSON字符串转换为JSONObject对象 JSONObje…...
Spring事务失效的几种情况
Spring事务失效的几种情况 1、未被Spring管理的类中的方法 这种情况是指:没有在类上添加Service、Repository、Component等注解将类交由Spring管理,然后该类中还有加上了Transactional注解 例如: Service //如果没有添加Service这个注解…...
filter的用法与使用场景:筛选数据
//this.allCollectorList:后台给定的所有可供选择数据 //this.collectorData:目前已经存在选中列表中的数据//目前已经存在选中列表中的数据id getSelIdList() {let eIdList = []this.collectorData.forEach(row => {eIdList.push(row.id)})return eIdList },//在中的数据…...
ClickHouse(18)ClickHouse集成ODBC表引擎详细解析
文章目录 创建表用法示例资料分享参考文章 ODBC集成表引擎使得ClickHouse可以通过ODBC方式连接到外部数据库. 为了安全地实现 ODBC 连接,ClickHouse 使用了一个独立程序 clickhouse-odbc-bridge. 如果ODBC驱动程序是直接从 clickhouse-server中加载的,那…...
网络攻击(一)--安全渗透简介
1. 安全渗透概述 目标 了解渗透测试的基本概念了解渗透测试从业人员的注意事项 1.1. 写在前面的话 在了解渗透测试之前,我们先看看,信息安全相关的法律是怎么样的 中华人民共和国网络安全法 《中华人民共和国网络安全法》由全国人民代表大会常务委员会…...
视频号小店资金需要多少?
我是电商珠珠 视频号团队于22年7月发展了自己的电商平台-视频号小店,相比于抖音电商来讲,可以有效的将公域流量转化为私域,对于商家来说,是一件利好的事情。 可以有效的提高客户的黏性,增加店铺回头客。 有很多想要…...
机器学习项目精选 第一期:超完整数据科学资料合集
大噶吼,不说废话,分享一波我最近看过并觉得非常硬核的资源,包括Python、机器学习、深度学习、大模型等等。 1、超完整数据科学资料合集 地址:https://github.com/krishnaik06/The-Grand-Complete-Data-Science-Materials Pytho…...
档案数字化管理可以提供什么服务?
档案数字化管理提供了便捷、高效和安全的档案管理服务,帮助组织更好地管理和利用自己的档案资源。 具体来说,专久智能档案数字化管理可以提供以下服务: 1. 档案扫描和数字化:将纸质档案通过扫描仪转换为数字格式,包括文…...
第一周:AI产品经理跳槽准备工作
一、筛选意向行业 因素1:行业发展情况 1. 行业发展情况和政策 待补充 2. AI人才市场情况 报告下载:待补充 2023年2⽉,ChatGPT爆⽕在脉脉引发各界搜索和热议,当⽉,“AIGC”、“⼈⼯智能”、“ChatGPT”、“⼤模型”等相关词汇搜索指数达到459.31,同⽐增⻓超5.4倍,内…...
基于核心素养高中物理“深度学习”策略及其教学研究课题论证设计方案
目录 一、课题的提出及意义 二、课题的核心概念及其界定...
通过 Java 17、Spring Boot 3.2 构建 Web API 应用程序
本心、输入输出、结果 文章目录 通过 Java 17、Spring Boot 3.2 构建 Web API 应用程序前言Spring Boot 3.2 更新了哪些内容Java 17 新特性构建步骤花有重开日,人无再少年实践是检验真理的唯一标准通过 Java 17、Spring Boot 3.2 构建 Web API 应用程序 编辑:简简单单 Online…...
go原生http开发简易blog(一)项目简介与搭建
文章目录 一、项目简介二、项目搭建前置知识三、首页- - -前端文件与后端结构体定义四、配置文件加载五、构造假数据- - -显示首页内容 代码地址:https://gitee.com/lymgoforIT/goblog 一、项目简介 使用Go原生http开发一个简易的博客系统,包含一下功能…...
[足式机器人]Part4 南科大高等机器人控制课 Ch09 Dynamics of Open Chains
本文仅供学习使用 本文参考: B站:CLEAR_LAB 笔者带更新-运动学 课程主讲教师: Prof. Wei Zhang 南科大高等机器人控制课 Ch09 Dynamics of Open Chains 1. Introduction1.1 From Single Rigid Body to Open Chains1.2 Preview of Open-Chain …...
概率论复习
第一章:随机概率及其概率 A和B相容就是 AB 空集 全概率公式与贝叶斯公式: 伯努利求概率: 第二章:一维随机变量及其分布: 离散型随机变量求分布律: 利用常规离散性分布求概率: 连续性随机变量…...
Spring AI与Spring Modulith核心技术解析
Spring AI核心架构解析 Spring AI(https://spring.io/projects/spring-ai)作为Spring生态中的AI集成框架,其核心设计理念是通过模块化架构降低AI应用的开发复杂度。与Python生态中的LangChain/LlamaIndex等工具类似,但特别为多语…...
在QWebEngineView上实现鼠标、触摸等事件捕获的解决方案
这个问题我看其他博主也写了,要么要会员、要么写的乱七八糟。这里我整理一下,把问题说清楚并且给出代码,拿去用就行,照着葫芦画瓢。 问题 在继承QWebEngineView后,重写mousePressEvent或event函数无法捕获鼠标按下事…...
Razor编程中@Html的方法使用大全
文章目录 1. 基础HTML辅助方法1.1 Html.ActionLink()1.2 Html.RouteLink()1.3 Html.Display() / Html.DisplayFor()1.4 Html.Editor() / Html.EditorFor()1.5 Html.Label() / Html.LabelFor()1.6 Html.TextBox() / Html.TextBoxFor() 2. 表单相关辅助方法2.1 Html.BeginForm() …...
MinIO Docker 部署:仅开放一个端口
MinIO Docker 部署:仅开放一个端口 在实际的服务器部署中,出于安全和管理的考虑,我们可能只能开放一个端口。MinIO 是一个高性能的对象存储服务,支持 Docker 部署,但默认情况下它需要两个端口:一个是 API 端口(用于存储和访问数据),另一个是控制台端口(用于管理界面…...
【C++】纯虚函数类外可以写实现吗?
1. 答案 先说答案,可以。 2.代码测试 .h头文件 #include <iostream> #include <string>// 抽象基类 class AbstractBase { public:AbstractBase() default;virtual ~AbstractBase() default; // 默认析构函数public:virtual int PureVirtualFunct…...
git: early EOF
macOS报错: Initialized empty Git repository in /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/.git/ remote: Enumerating objects: 2691797, done. remote: Counting objects: 100% (1760/1760), done. remote: Compressing objects: 100% (636/636…...
DAY 26 函数专题1
函数定义与参数知识点回顾:1. 函数的定义2. 变量作用域:局部变量和全局变量3. 函数的参数类型:位置参数、默认参数、不定参数4. 传递参数的手段:关键词参数5 题目1:计算圆的面积 任务: 编写一…...
数据库正常,但后端收不到数据原因及解决
从代码和日志来看,后端SQL查询确实返回了数据,但最终user对象却为null。这表明查询结果没有正确映射到User对象上。 在前后端分离,并且ai辅助开发的时候,很容易出现前后端变量名不一致情况,还不报错,只是单…...
结构化文件管理实战:实现目录自动创建与归类
手动操作容易因疲劳或疏忽导致命名错误、路径混乱等问题,进而引发后续程序异常。使用工具进行标准化操作,能有效降低出错概率。 需要快速整理大量文件的技术用户而言,这款工具提供了一种轻便高效的解决方案。程序体积仅有 156KB,…...
Linux入门课的思维导图
耗时两周,终于把慕课网上的Linux的基础入门课实操、总结完了! 第一次以Blog的形式做学习记录,过程很有意思,但也很耗时。 课程时长5h,涉及到很多专有名词,要去逐个查找,以前接触过的概念因为时…...
