百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

七爪源码:如何使用 SQLite 数据库在 Flutter 中保存大数据

wptr33 2025-04-26 21:40 37 浏览

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/小程序/网站源码资源!

相关推荐

oracle数据导入导出_oracle数据导入导出工具

关于oracle的数据导入导出,这个功能的使用场景,一般是换服务环境,把原先的oracle数据导入到另外一台oracle数据库,或者导出备份使用。只不过oracle的导入导出命令不好记忆,稍稍有点复杂...

继续学习Python中的while true/break语句

上次讲到if语句的用法,大家在微信公众号问了小编很多问题,那么小编在这几种解决一下,1.else和elif是子模块,不能单独使用2.一个if语句中可以包括很多个elif语句,但结尾只能有一个...

python continue和break的区别_python中break语句和continue语句的区别

python中循环语句经常会使用continue和break,那么这2者的区别是?continue是跳出本次循环,进行下一次循环;break是跳出整个循环;例如:...

简单学Python——关键字6——break和continue

Python退出循环,有break语句和continue语句两种实现方式。break语句和continue语句的区别:break语句作用是终止循环。continue语句作用是跳出本轮循环,继续下一次循...

2-1,0基础学Python之 break退出循环、 continue继续循环 多重循

用for循环或者while循环时,如果要在循环体内直接退出循环,可以使用break语句。比如计算1至100的整数和,我们用while来实现:sum=0x=1whileTrue...

Python 中 break 和 continue 傻傻分不清

大家好啊,我是大田。...

python中的流程控制语句:continue、break 和 return使用方法

Python中,continue、break和return是控制流程的关键语句,用于在循环或函数中提前退出或跳过某些操作。它们的用途和区别如下:1.continue(跳过当前循环的剩余部分,进...

L017:continue和break - 教程文案

continue和break在Python中,continue和break是用于控制循环(如for和while)执行流程的关键字,它们的作用如下:1.continue:跳过当前迭代,...

作为前端开发者,你都经历过怎样的面试?

已经裸辞1个月了,最近开始投简历找工作,遇到各种各样的面试,今天分享一下。其实在职的时候也做过面试官,面试官时,感觉自己问的问题很难区分候选人的能力,最好的办法就是看看候选人的github上的代码仓库...

面试被问 const 是否不可变?这样回答才显功底

作为前端开发者,我在学习ES6特性时,总被const的"善变"搞得一头雾水——为什么用const声明的数组还能push元素?为什么基本类型赋值就会报错?直到翻遍MDN文档、对着内存图反...

2023金九银十必看前端面试题!2w字精品!

导文2023金九银十必看前端面试题!金九银十黄金期来了想要跳槽的小伙伴快来看啊CSS1.请解释CSS的盒模型是什么,并描述其组成部分。...

前端面试总结_前端面试题整理

记得当时大二的时候,看到实验室的学长学姐忙于各种春招,有些收获了大厂offer,有些还在苦苦面试,其实那时候的心里还蛮忐忑的,不知道自己大三的时候会是什么样的一个水平,所以从19年的寒假放完,大二下学...

由浅入深,66条JavaScript面试知识点(七)

作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录...

2024前端面试真题之—VUE篇_前端面试题vue2020及答案

添加图片注释,不超过140字(可选)...

今年最常见的前端面试题,你会做几道?

在面试或招聘前端开发人员时,期望、现实和需求之间总是存在着巨大差距。面试其实是一个交流想法的地方,挑战人们的思考方式,并客观地分析给定的问题。可以通过面试了解人们如何做出决策,了解一个人对技术和解决问...