当前位置: 首页 > 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; 连续性随机变量…...

B站缓存视频转换终极指南:3分钟学会永久保存珍贵内容

B站缓存视频转换终极指南&#xff1a;3分钟学会永久保存珍贵内容 【免费下载链接】m4s-converter 一个跨平台小工具&#xff0c;将bilibili缓存的m4s格式音视频文件合并成mp4 项目地址: https://gitcode.com/gh_mirrors/m4/m4s-converter 你是否曾为B站视频突然下架而措…...

从BERT到Phi-4:跨模型架构的Python微调配置迁移图谱(含17个开源模型实测yaml模板,仅开放72小时)

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;Python微调配置的演进逻辑与统一范式 Python 微调&#xff08;Fine-tuning&#xff09;配置体系经历了从硬编码参数 → YAML 配置驱动 → 声明式配置即代码&#xff08;Configuration-as-Code&#xff…...

绝地求生智能辅助优化:从新手到高手的实战进阶指南

绝地求生智能辅助优化&#xff1a;从新手到高手的实战进阶指南 【免费下载链接】logitech-pubg PUBG no recoil script for Logitech gaming mouse / 绝地求生 罗技 鼠标宏 项目地址: https://gitcode.com/gh_mirrors/lo/logitech-pubg 在《绝地求生》的激烈对战中&…...

从设计师的PS画布到程序员的SVG:用viewBox和width/height讲清楚‘画布’与‘视口’的区别

从设计师的PS画布到程序员的SVG&#xff1a;用viewBox和width/height讲清楚‘画布’与‘视口’的区别 当你第一次把精心设计的矢量图标从Illustrator导出为SVG格式&#xff0c;却发现它在网页上显示得要么太小、要么太大&#xff0c;甚至只显示了一部分——这不是你的设计有问题…...

嵌入式C农业传感器驱动性能瓶颈突破(从87ms响应延迟压降至12.3ms,实测功耗降低41%)

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;嵌入式C农业传感器驱动性能瓶颈突破&#xff08;从87ms响应延迟压降至12.3ms&#xff0c;实测功耗降低41%&#xff09; 在农田微气候监测节点中&#xff0c;传统基于轮询的DHT22ADS1115复合驱动常因阻塞…...

Claude桌面应用深度配置指南:打造个性化AI开发工作流

1. 项目概述&#xff1a;一个为Claude桌面应用量身定制的配置仓库如果你和我一样&#xff0c;是Claude桌面应用的深度用户&#xff0c;同时又对代码编辑、终端操作和日常开发流程有着近乎苛刻的效率追求&#xff0c;那么你很可能已经对应用默认的配置感到“意犹未尽”。Claude本…...

Sunshine游戏串流完全指南:3步搭建你的跨平台游戏服务器

Sunshine游戏串流完全指南&#xff1a;3步搭建你的跨平台游戏服务器 【免费下载链接】Sunshine Self-hosted game stream host for Moonlight. 项目地址: https://gitcode.com/GitHub_Trending/su/Sunshine 你是否想在客厅电视上玩PC游戏&#xff0c;或者用平板继续你的…...

ClawLodge:OpenClaw生态的配置共享中心与AI智能体开发加速器

1. 项目概述&#xff1a;ClawLodge&#xff0c;一个OpenClaw生态的“应用商店”如果你正在使用或关注OpenClaw&#xff0c;一个新兴的、以“龙虾”为代号的智能体开发框架&#xff0c;那么你很可能已经体会过它的强大与灵活。OpenClaw允许开发者像搭积木一样&#xff0c;通过配…...

TaoCarts 反向海淘系统:基于 Spring Cloud 的微服务架构设计与高并发实践

四、自动化代采系统的核心实现1688 自动代采是反向海淘系统的核心竞争力之一。TaoCarts 的代采模块采用了以下技术方案&#xff1a;- 多账号轮询&#xff1a;维护 1688 采购账号池&#xff0c;通过权重策略自动分配采购任务&#xff0c;避免单账号触发风控- 智能价格监控&#…...

Zed 1.0 编辑器深度评测与实战指南

每次打开重型 IDE 等待进度条走完&#xff0c;或者在老旧笔记本上因为内存爆满而卡顿时&#xff0c;开发者对“轻量且快速”的渴望就会达到顶峰。我们习惯了在启动速度和功能丰富度之间做妥协&#xff0c;直到 Zed 1.0 的正式发布打破了这种平衡。这款由 Atom 原班人马打造的编…...