Flutter数据库查询插件jaguar_query_sqflite的使用

Flutter数据库查询插件jaguar_query_sqflite的使用

jaguar_query_sqflite 是一个基于 sqflite 的适配器,用于与 jaguar_queryjaguar_orm 配合使用。它允许开发者通过简洁的 DSL(领域特定语言)来操作 SQLite 数据库。

使用方法

以下是一个简单的使用示例:

1. 导入必要的包

import 'dart:io';
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:jaguar_query_sqflite/jaguar_query_sqflite.dart';

2. 定义数据模型

class Post {
  Post();

  Post.make(this.id, this.msg, this.author);

  int id;
  String msg;
  String author;

  @override
  String toString() => '$id $msg $author';
}

3. 创建数据表适配器

SqfliteAdapter _adapter;

4. 定义数据表 Bean

class PostBean {
  // 定义字段
  final IntField id = new IntField('_id');
  final StrField msg = new StrField('msg');
  final StrField author = new StrField('author');

  // 表名
  String get tableName => 'posts';

  // 创建表
  Future<void> createTable() async {
    final st = new Create(tableName, ifNotExists: true)
        .addInt('_id', primary: true)
        .addStr('msg', isNullable: true)
        .addStr('author', isNullable: true);

    await _adapter.createTable(st);
  }

  // 插入数据
  Future<int> insert(Post post) async {
    Insert inserter = new Insert(tableName);

    inserter.set(id, post.id);
    inserter.set(msg, post.msg);
    inserter.set(author, post.author);

    return await _adapter.insert(inserter);
  }

  // 更新数据
  Future<int> update(int id, String author) async {
    Update updater = new Update(tableName);
    updater.where(this.id.eq(id));
    updater.set(this.author, author);

    return await _adapter.update(updater);
  }

  // 查找单条数据
  Future<Post> findOne(int id) async {
    Find finder = new Find(tableName);
    finder.where(this.id.eq(id));

    Map<String, dynamic> map = await _adapter.findOne(finder);

    Post post = new Post();
    post.id = map['_id'];
    post.msg = map['msg'];
    post.author = map['author'];

    return post;
  }

  // 查找所有数据
  Future<List<Post>> findAll() async {
    Find finder = new Find(tableName);
    List<Map<String, dynamic>> maps = await (await _adapter.find(finder)).toList();

    List<Post> posts = [];

    for (var map in maps) {
      Post post = new Post();
      post.id = map['_id'];
      post.msg = map['msg'];
      post.author = map['author'];
      posts.add(post);
    }

    return posts;
  }

  // 删除单条数据
  Future<int> remove(int id) async {
    Remove remover = new Remove(tableName);
    remover.where(this.id.eq(id));

    return await _adapter.remove(remover);
  }

  // 删除所有数据
  Future<int> removeAll() async {
    Remove remover = new Remove(tableName);
    return await _adapter.remove(remover);
  }
}

5. 主函数执行逻辑

void main() async {
  // 初始化适配器
  _adapter = new SqfliteAdapter(await getDatabasesPath());
  await _adapter.connect();

  // 实例化 Bean
  final bean = new PostBean();

  // 创建表
  await bean.createTable();

  // 清空表数据
  await bean.removeAll();

  // 插入数据
  await bean.insert(new Post.make(1, 'Whatever 1', 'mark'));
  await bean.insert(new Post.make(2, 'Whatever 2', 'bob'));

  // 查询单条数据
  Post post = await bean.findOne(1);
  print(post);

  // 查询所有数据
  List<Post> posts = await bean.findAll();
  print(posts);

  // 更新数据
  await bean.update(1, 'rowling');

  // 再次查询单条数据
  post = await bean.findOne(1);
  print(post);

  // 删除数据
  await bean.remove(1);
  await bean.remove(2);

  // 尝试查询已删除的数据
  try {
    post = await bean.findOne(1);
    print(post);
  } on JaguarOrmException catch (e) {
    print(e);
  }

  // 关闭连接
  await _adapter.close();
  exit(0);
}

运行结果

运行上述代码后,控制台将输出类似以下内容:

Instance of 'Post'
[Instance of 'Post']
Instance of 'Post'
Error: No such record found

更多关于Flutter数据库查询插件jaguar_query_sqflite的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据库查询插件jaguar_query_sqflite的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


jaguar_query_sqflite 是一个用于在 Flutter 应用中执行 SQLite 数据库查询的插件。它是 jaguar_query 库的一部分,专门为 Flutter 和 Dart 设计,提供了类型安全和易于使用的 API 来操作 SQLite 数据库。

以下是如何在 Flutter 项目中使用 jaguar_query_sqflite 的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 jaguar_query_sqflite 依赖:

dependencies:
  flutter:
    sdk: flutter
  jaguar_query_sqflite: ^3.0.0

然后运行 flutter pub get 来安装依赖。

2. 创建数据库模型

定义一个数据库模型类,并使用 jaguar_query 的注解来映射到数据库表。

import 'package:jaguar_query_sqflite/jaguar_query_sqflite.dart';
import 'package:jaguar_orm/jaguar_orm.dart';

part 'user_model.g.dart';

class User {
  @PrimaryKey()
  int id;

  @Column()
  String name;

  @Column()
  int age;

  User({this.id, this.name, this.age});
}

@GenBean()
class UserBean extends Bean<User> with _UserBean {
  UserBean(Adapter adapter) : super(adapter);

  [@override](/user/override)
  String get tableName => 'users';
}

3. 生成代码

运行以下命令来生成 ORM 代码:

flutter pub run build_runner build

这将生成 user_model.g.dart 文件,其中包含 UserBean 的实现。

4. 初始化数据库

在 Flutter 应用中初始化数据库并创建表。

import 'package:jaguar_query_sqflite/jaguar_query_sqflite.dart';
import 'user_model.dart';

Future<void> main() async {
  final adapter = SqfliteAdapter('my_database.db');
  await adapter.connect();

  final userBean = UserBean(adapter);
  await userBean.createTable();
}

5. 执行 CRUD 操作

使用生成的 UserBean 类来执行 CRUD 操作。

插入数据

final user = User(id: 1, name: 'John Doe', age: 30);
await userBean.insert(user);

查询数据

final user = await userBean.find(1);
print('User: ${user.name}, Age: ${user.age}');

更新数据

user.age = 31;
await userBean.update(user);

删除数据

await userBean.delete(1);

6. 关闭数据库连接

在应用退出时,关闭数据库连接。

await adapter.close();

完整示例

以下是一个完整的示例,展示了如何使用 jaguar_query_sqflite 进行数据库操作:

import 'package:flutter/material.dart';
import 'package:jaguar_query_sqflite/jaguar_query_sqflite.dart';
import 'user_model.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final adapter = SqfliteAdapter('my_database.db');
  await adapter.connect();

  final userBean = UserBean(adapter);
  await userBean.createTable();

  // Insert a user
  final user = User(id: 1, name: 'John Doe', age: 30);
  await userBean.insert(user);

  // Query the user
  final queriedUser = await userBean.find(1);
  print('User: ${queriedUser.name}, Age: ${queriedUser.age}');

  // Update the user
  queriedUser.age = 31;
  await userBean.update(queriedUser);

  // Delete the user
  await userBean.delete(1);

  await adapter.close();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Jaguar Query Sqflite Example'),
        ),
        body: Center(
          child: Text('Check the console for database operations!'),
        ),
      ),
    );
  }
}
回到顶部