当前位置: 首页 > news >正文

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插件数据库应用

前言 今天在观阅掘金大佬文章的时候&#xff0c;了解到了该 sqflite 插件&#xff0c;结合官网教程和自己实践&#xff0c;由此总结出该文&#xff0c;希望对大家的学习有帮助&#xff01; 插件详情 Flutter的 SQLite 插件。支持 iOS、Android 和 MacOS。 支持事务和batch模式…...

OxLint 发布了,Eslint 何去何从?

由于最近的rust在前端领域的崛起&#xff0c;基于rust的前端生态链遭到rust底层重构&#xff0c;最近又爆出OxLint&#xff0c;是一款基于Rust的linter工具Oxlint在国外前端圈引起热烈讨论&#xff0c;很多大佬给出了高度评价&#xff1b;你或许不知道OxLint&#xff0c;相比ES…...

第一次使用ThreadPoolExecutor处理业务

通过对业务逻辑的分析&#xff0c;进行编码&#xff0c;先把第一条sql查出来的数据进行分组&#xff0c;然后分别使用不同的线程去查询数据返回&#xff0c;并添加到原来的数据中。 总感觉哪里写的不对&#xff0c;但是同事们都没用过这个&#xff0c;请大家指教一下&#xff…...

Sharding-Jdbc(6):Sharding-Jdbc日志分析

1 修改配置 将配置文件中的开启分片日志从false改为true Sharding-JDBC中的路由结果是通过分片字段和分片方法来确定的,如果查询条件中有 id 字段的情况还好&#xff0c;查询将会落到某个具体的分片&#xff1b;如果查询没有分片的字段&#xff0c;会向所有的db或者是表都会查…...

centos安装了curl却报 -bash: curl: command not found

前因 我服务器上想用curl下载docker-compress&#xff0c;发现没有curl命令&#xff0c;就去下载安装&#xff0c;安装完成之后&#xff0c;报-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博文目录 诸神缄默不语的论文阅读笔记和分类 论文名称&#xff1a;REALM: Retrieval-Augmented Language Model Pre-Training 模型名称&#xff1a;Retrieval-Augmented Language Model pre-training (REALM) 本文是2020年ICML论文&#xff0c;作者来自…...

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管理的类中的方法 这种情况是指&#xff1a;没有在类上添加Service、Repository、Component等注解将类交由Spring管理&#xff0c;然后该类中还有加上了Transactional注解 例如&#xff1a; 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 连接&#xff0c;ClickHouse 使用了一个独立程序 clickhouse-odbc-bridge. 如果ODBC驱动程序是直接从 clickhouse-server中加载的&#xff0c;那…...

网络攻击(一)--安全渗透简介

1. 安全渗透概述 目标 了解渗透测试的基本概念了解渗透测试从业人员的注意事项 1.1. 写在前面的话 在了解渗透测试之前&#xff0c;我们先看看&#xff0c;信息安全相关的法律是怎么样的 中华人民共和国网络安全法 《中华人民共和国网络安全法》由全国人民代表大会常务委员会…...

视频号小店资金需要多少?

我是电商珠珠 视频号团队于22年7月发展了自己的电商平台-视频号小店&#xff0c;相比于抖音电商来讲&#xff0c;可以有效的将公域流量转化为私域&#xff0c;对于商家来说&#xff0c;是一件利好的事情。 可以有效的提高客户的黏性&#xff0c;增加店铺回头客。 有很多想要…...

机器学习项目精选 第一期:超完整数据科学资料合集

大噶吼&#xff0c;不说废话&#xff0c;分享一波我最近看过并觉得非常硬核的资源&#xff0c;包括Python、机器学习、深度学习、大模型等等。 1、超完整数据科学资料合集 地址&#xff1a;https://github.com/krishnaik06/The-Grand-Complete-Data-Science-Materials Pytho…...

档案数字化管理可以提供什么服务?

档案数字化管理提供了便捷、高效和安全的档案管理服务&#xff0c;帮助组织更好地管理和利用自己的档案资源。 具体来说&#xff0c;专久智能档案数字化管理可以提供以下服务&#xff1a; 1. 档案扫描和数字化&#xff1a;将纸质档案通过扫描仪转换为数字格式&#xff0c;包括文…...

第一周: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(一)项目简介与搭建

文章目录 一、项目简介二、项目搭建前置知识三、首页- - -前端文件与后端结构体定义四、配置文件加载五、构造假数据- - -显示首页内容 代码地址&#xff1a;https://gitee.com/lymgoforIT/goblog 一、项目简介 使用Go原生http开发一个简易的博客系统&#xff0c;包含一下功能…...

[足式机器人]Part4 南科大高等机器人控制课 Ch09 Dynamics of Open Chains

本文仅供学习使用 本文参考&#xff1a; B站&#xff1a;CLEAR_LAB 笔者带更新-运动学 课程主讲教师&#xff1a; Prof. Wei Zhang 南科大高等机器人控制课 Ch09 Dynamics of Open Chains 1. Introduction1.1 From Single Rigid Body to Open Chains1.2 Preview of Open-Chain …...

概率论复习

第一章&#xff1a;随机概率及其概率 A和B相容就是 AB 空集 全概率公式与贝叶斯公式&#xff1a; 伯努利求概率&#xff1a; 第二章&#xff1a;一维随机变量及其分布&#xff1a; 离散型随机变量求分布律&#xff1a; 利用常规离散性分布求概率&#xff1a; 连续性随机变量…...

在软件开发中正确使用MySQL日期时间类型的深度解析

在日常软件开发场景中&#xff0c;时间信息的存储是底层且核心的需求。从金融交易的精确记账时间、用户操作的行为日志&#xff0c;到供应链系统的物流节点时间戳&#xff0c;时间数据的准确性直接决定业务逻辑的可靠性。MySQL作为主流关系型数据库&#xff0c;其日期时间类型的…...

盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来

一、破局&#xff1a;PCB行业的时代之问 在数字经济蓬勃发展的浪潮中&#xff0c;PCB&#xff08;印制电路板&#xff09;作为 “电子产品之母”&#xff0c;其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透&#xff0c;PCB行业面临着前所未有的挑战与机遇。产品迭代…...

OkHttp 中实现断点续传 demo

在 OkHttp 中实现断点续传主要通过以下步骤完成&#xff0c;核心是利用 HTTP 协议的 Range 请求头指定下载范围&#xff1a; 实现原理 Range 请求头&#xff1a;向服务器请求文件的特定字节范围&#xff08;如 Range: bytes1024-&#xff09; 本地文件记录&#xff1a;保存已…...

【android bluetooth 框架分析 04】【bt-framework 层详解 1】【BluetoothProperties介绍】

1. BluetoothProperties介绍 libsysprop/srcs/android/sysprop/BluetoothProperties.sysprop BluetoothProperties.sysprop 是 Android AOSP 中的一种 系统属性定义文件&#xff08;System Property Definition File&#xff09;&#xff0c;用于声明和管理 Bluetooth 模块相…...

【Zephyr 系列 10】实战项目:打造一个蓝牙传感器终端 + 网关系统(完整架构与全栈实现)

🧠关键词:Zephyr、BLE、终端、网关、广播、连接、传感器、数据采集、低功耗、系统集成 📌目标读者:希望基于 Zephyr 构建 BLE 系统架构、实现终端与网关协作、具备产品交付能力的开发者 📊篇幅字数:约 5200 字 ✨ 项目总览 在物联网实际项目中,**“终端 + 网关”**是…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题&#xff1a;docker pull 失败 网络不同&#xff0c;需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

深度学习习题2

1.如果增加神经网络的宽度&#xff0c;精确度会增加到一个特定阈值后&#xff0c;便开始降低。造成这一现象的可能原因是什么&#xff1f; A、即使增加卷积核的数量&#xff0c;只有少部分的核会被用作预测 B、当卷积核数量增加时&#xff0c;神经网络的预测能力会降低 C、当卷…...

安宝特案例丨Vuzix AR智能眼镜集成专业软件,助力卢森堡医院药房转型,赢得辉瑞创新奖

在Vuzix M400 AR智能眼镜的助力下&#xff0c;卢森堡罗伯特舒曼医院&#xff08;the Robert Schuman Hospitals, HRS&#xff09;凭借在无菌制剂生产流程中引入增强现实技术&#xff08;AR&#xff09;创新项目&#xff0c;荣获了2024年6月7日由卢森堡医院药剂师协会&#xff0…...

iview框架主题色的应用

1.下载 less要使用3.0.0以下的版本 npm install less2.7.3 npm install less-loader4.0.52./src/config/theme.js文件 module.exports {yellow: {theme-color: #FDCE04},blue: {theme-color: #547CE7} }在sass中使用theme配置的颜色主题&#xff0c;无需引入&#xff0c;直接可…...

GO协程(Goroutine)问题总结

在使用Go语言来编写代码时&#xff0c;遇到的一些问题总结一下 [参考文档]&#xff1a;https://www.topgoer.com/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine.html 1. main()函数默认的Goroutine 场景再现&#xff1a; 今天在看到这个教程的时候&#xff0c;在自己的电…...