七爪源码:如何使用 SQLite 数据库在 Flutter 中保存大数据
wptr33 2025-04-26 21:40 17 浏览
SQLite 是一个开源、零配置、自包含、独立的事务关系数据库引擎,旨在嵌入到应用程序中。
sqflite
Flutter 的 SQLite 插件。 支持 iOS、Android 和 MacOS。
- 支持事务和批处理
- 打开期间的自动版本管理
- 插入/查询/更新/删除查询的助手
- 在 iOS 和 Android 上的后台线程中执行的 DB 操作
其他平台支持:
- 使用 sqflite_common_ffi 支持 Linux/Windows/DartVM
- 不支持网络。
使用示例:
- notepad_sqflite:适用于 iOS/Android/Windows/linux/Mac 的简单颤振记事本
入门
在您的颤振项目中添加依赖项:
dependencies:
...
sqflite:
如需帮助开始使用 Flutter,请查看在线文档。
导入 sqflite.dart
import 'package:sqflite/sqflite.dart';
打开数据库
SQLite 数据库是文件系统中由路径标识的文件。 如果是relative,则该路径是相对于getDatabasesPath()获取的路径,是Android默认的数据库目录,iOS/MacOS默认的documents目录。
var db = await openDatabase('my_db.db');
有一个基本的迁移机制来处理打开期间的架构更改。
许多应用程序使用一个数据库并且永远不需要关闭它(它会在应用程序终止时关闭)。 如果要释放资源,可以关闭数据库。
await db.close();
- 查看有关打开数据库的更多信息。
- 完整迁移示例
原始 SQL 查询
执行原始 SQL 查询的演示代码
// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
// Delete the database
await deleteDatabase(path);
// open the database
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// When creating the db, create the table
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
// Insert some records in a transaction
await database.transaction((txn) async {
int id1 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
print('inserted1: $id1');
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
print('inserted2: $id2');
});
// Update some record
int count = await database.rawUpdate(
'UPDATE Test SET name = ?, value = ? WHERE name = ?',
['updated name', '9876', 'some name']);
print('updated: $count');
// Get the records
List<Map> list = await database.rawQuery('SELECT * FROM Test');
List<Map> expectedList = [
{'name': 'updated name', 'id': 1, 'value': 9876, 'num': 456.789},
{'name': 'another name', 'id': 2, 'value': 12345678, 'num': 3.1416}
];
print(list);
print(expectedList);
assert(const DeepCollectionEquality().equals(list, expectedList));
// Count the records
count = Sqflite
.firstIntValue(await database.rawQuery('SELECT COUNT(*) FROM Test'));
assert(count == 2);
// Delete a record
count = await database
.rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
assert(count == 1);
// Close the database
await database.close();
关于 SQL 的基本信息在这里。
SQL 助手
使用助手的示例
final String tableTodo = 'todo';
final String columnId = '_id';
final String columnTitle = 'title';
final String columnDone = 'done';
class Todo {
int id;
String title;
bool done;
Map<String, Object?> toMap() {
var map = <String, Object?>{
columnTitle: title,
columnDone: done == true ? 1 : 0
};
if (id != null) {
map[columnId] = id;
}
return map;
}
Todo();
Todo.fromMap(Map<String, Object?> map) {
id = map[columnId];
title = map[columnTitle];
done = map[columnDone] == 1;
}
}
class TodoProvider {
Database db;
Future open(String path) async {
db = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table $tableTodo (
$columnId integer primary key autoincrement,
$columnTitle text not null,
$columnDone integer not null)
''');
});
}
Future<Todo> insert(Todo todo) async {
todo.id = await db.insert(tableTodo, todo.toMap());
return todo;
}
Future<Todo> getTodo(int id) async {
List<Map> maps = await db.query(tableTodo,
columns: [columnId, columnDone, columnTitle],
where: '$columnId = ?',
whereArgs: [id]);
if (maps.length > 0) {
return Todo.fromMap(maps.first);
}
return null;
}
Future<int> delete(int id) async {
return await db.delete(tableTodo, where: '$columnId = ?', whereArgs: [id]);
}
Future<int> update(Todo todo) async {
return await db.update(tableTodo, todo.toMap(),
where: '$columnId = ?', whereArgs: [todo.id]);
}
Future close() async => db.close();
}
阅读结果
假设读取结果如下:
List<Map<String, Object?>> records = await db.query('my_table');
生成的地图项是只读的
// get the first record
Map<String, Object?> mapRead = records.first;
// Update it in memory...this will throw an exception
mapRead['my_column'] = 1;
// Crash... `mapRead` is read-only
如果要在内存中修改它,则需要创建一个新映射:
// get the first record
Map<String, Object?> map = Map<String, Object?>.from(mapRead);
// Update it in memory now
map['my_column'] = 1;
交易
不使用数据库,只使用事务中的 Transaction 对象来访问数据库。 请记住,回调 onCreate onUpgrade onDowngrade 已在内部包装在事务中,因此无需将您的语句包装在这些回调中的事务中。
await database.transaction((txn) async {
// Ok
await txn.execute('CREATE TABLE Test1 (id INTEGER PRIMARY KEY)');
// DON'T use the database object in a transaction
// this will deadlock!
await database.execute('CREATE TABLE Test2 (id INTEGER PRIMARY KEY)');
});
如果回调没有抛出错误,则提交事务。 如果抛出错误,则取消事务。 因此,回滚事务的一种方法是抛出异常。
Batch 支持
为了避免 dart 和本机代码之间的乒乓,您可以使用 Batch:
batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();
获取每个操作的结果是有代价的(插入的 id 以及更新和删除的更改次数),尤其是在执行额外 SQL 请求的 Android 上。 如果您不关心结果并担心大批量的性能,您可以使用
await batch.commit(noResult: true);
警告,在事务期间,直到事务提交后才会提交批处理
await database.transaction((txn) async {
var batch = txn.batch();
// ...
// commit but the actual commit will happen when the transaction is committed
// however the data is available in this transaction
await batch.commit();
// ...
});
默认情况下,批处理一旦遇到错误就会停止(这通常会还原未提交的更改)。 您可以忽略错误,以便运行并提交每个成功的操作,即使一个操作失败:
await batch.commit(continueOnError: true);
表名和列名
一般来说,最好避免对实体名称使用 SQLite 关键字。 如果使用以下任何名称:
"add","all","alter","and","as","autoincrement","between","case","check","collate","commit","constraint","create","default","deferrable","delete","distinct","drop","else","escape","except","exists","foreign","from","group","having","if","in","index","insert","intersect","into","is","isnull","join","limit","not","notnull","null","on","or","order","primary","references","select","set","table","then","to","transaction","union","unique","update","using","values","when","where"
助手将转义名称,即
db.query('table')
将相当于手动在表名周围添加双引号(这里命名为表令人困惑)
db.rawQuery('SELECT * FROM "table"');
但是,在任何其他原始语句(包括 orderBy、where、groupBy)中,请确保使用双引号正确转义名称。 例如,请参见下面的列名组未在 columns 参数中转义,但在 where 参数中转义。
db.query('table', columns: ['group'], where: '"group" = ?', whereArgs: ['my_group']);
支持的 SQLite 类型
尚未对值进行有效性检查,因此请避免不支持的类型
https://www.sqlite.org/datatype3.html
DateTime 不是受支持的 SQLite 类型。我个人将它们存储为 int (millisSinceEpoch) 或 string (iso8601)
bool 不是受支持的 SQLite 类型。使用 INTEGER 和 0 和 1 值。
有关支持的类型的更多信息,请点击此处。
整数
- 飞镖类型:int
- 支持的值:从 -2^63 到 2^63 - 1
真实的
- 飞镖类型:num
文本
- 飞镖类型:字符串
斑点
- 飞镖类型:Uint8List
目前的问题
由于事务在 SQLite(线程)中的工作方式,不支持并发读写事务。当前所有调用都是同步的,事务块是独占的。我认为支持并发访问的基本方法是多次打开数据库,但它仅适用于 iOS,因为 Android 重用相同的数据库对象。我还认为本机线程可能是未来潜在的解决方案,但是在 android 上访问另一个线程中的数据库在事务中被阻止......
关注七爪网,获取更多APP/小程序/网站源码资源!
相关推荐
- 「网络安全」JAVA代码审计——XXE外部实体注入
-
一、WEB安全部分想要了解XXE,在那之前需要了解XML的相关基础二、XML基础...
- Web前端面试题目及答案汇总(web前端面试题最新)
-
Web前端面试题目及答案汇总来源:极客头条以下是收集一些面试中经常会遇到的经典面试题以及自己面试过程中无法解决的问题,通过对知识的整理以及经验的总结,重新巩固自身的前端基础知识,如有错误或更好的答案,...
- 什么是脚本文件?与可执行文件有什么不同?
-
今天的内容是脚本文件和可执行文件是两种不同类型的计算机文件,它们在结构和执行方式上有显著区别。脚本文件:定义与特性...
- 20个实用Python运维脚本(收藏级)(python 运维工具)
-
系统环境:支持Linux(Ubuntu/CentOS/Debian)和Windows...
- 2026年前每个开发者都应该学习的技能
-
优秀开发者...
- Linux 如何每 5、10、15 或 30 分钟运行一次 Cron 作业?
-
在Linux系统中,Cron是一个强大的工具,用于自动化重复性任务。通过合理配置...
- Shell脚本编程进阶实战:从入门到高效自动化
-
Shell脚本编程进阶实战:从入门到高效自动化一、参数处理进阶:打造专业级CLI工具1.高级参数解析示例...
- 在Bash中按分隔符拆分字符串的方法
-
技术背景在Bash脚本编程中,经常会遇到需要按特定分隔符拆分字符串的需求,例如处理CSV文件、解析日志等。掌握字符串拆分的方法对于数据处理和脚本自动化非常重要。...
- 程序员用5分钟,把一个400多MB的苹果安装包削掉了187MB
-
丰色发自凹非寺量子位|公众号QbitAI前些日子,一个...
- 如何在 Windows 上编写批处理脚本
-
你知道如何使用命令提示符吗?如果这样做,您可以编写一个批处理文件。在最简单的形式中,批处理文件(或批处理脚本)是双击文件时执行的几个命令的列表。批处理文件一直回到DOS,但仍然适用于现代版本的Win...
- 一文搞懂shell脚本(shell脚本应用实战)
-
一文搞懂shell脚本1、shell脚本介绍什么是shell脚本...
- 一文讲清ShellScript脚本编程知识
-
摘要:本文详尽地讲述了ShellScript的基础内容,还有它在Linux系统里的运用情况,涵盖了它的基本语法、常用的命令以及高级的功能。ShellScript可是一种简单又非常实用的编...
- 在Bash脚本中获取自身所在目录的方法
-
技术背景在使用Bash脚本时,有时需要获取脚本自身所在的目录。比如,当脚本作为另一个应用程序的启动器时,需要将工作目录更改为脚本所在的目录,以便对该目录中的文件进行操作。然而,由于脚本的调用方式多样(...
- shell中如何确定脚本的位置?这篇文章告诉你
-
我想从同一个位置读取一些配置文件,如何确定脚本的位置?。这个问题的出现主要是由两个原因引发的:一是您希望将脚本的数据或配置进行外部化,因此需要一种方式来寻找这些外部资源;二是您的脚本需要对某些捆绑资源...
- bash shell 语法(bash命令用法)
-
下面是**Shell(Bash)语法的常用知识点总结**,适合初学者和日常脚本编写参考。内容涵盖变量、判断、循环、函数、重定向、正则、数组等常见用法。---#Shell(Bash)语法速查总结...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
面试官:git pull是哪两个指令的组合?
-
git 执行pull错误如何撤销 git pull fail
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)