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

无涯教程-Flutter - 数据库

SQLite" class="css-1occaib">SQLite数据库是基于事实和标准SQL的嵌入式数据库引擎,它是小型且经过时间考验的数据库引擎,sqflite软件包提供了许多函数,可以有效地与SQLite数据库一起使用,它提供了操作SQLite数据库引擎的标准方法。

  • 在Android Studio中创建一个新的Flutter应用程序product_sqlite_app。

  • 用无涯教程的 product_rest_app 代码替换默认的启动代码(main.dart)。

  • 将assets文件夹从 product_nav_app 复制到 product_rest_app 并在* pubspec.yaml`文件内添加assets。

flutter: assets: - assets/appimages/floppy.png - assets/appimages/iphone.png - assets/appimages/laptop.png - assets/appimages/pendrive.png - assets/appimages/pixel.png - assets/appimages/tablet.png
  • 在pubspec.yaml文件中配置sqflite软件包,如下所示-

dependencies: sqflite: any
  • 在pubspec.yaml文件中配置path_provider软件包,如下所示-

dependencies: path_provider: any
  • 此处,path_provider软件包用于获取系统的临时文件夹路径和应用程序的路径,使用 sqflite 的最新版本号代替任何。

  • Android Studio会提醒pubspec.yaml已更新。

Updated
  • 单击"Get dependencies"选项。 Android studio将从互联网上获取该软件包,并为应用程序正确配置它。

  • 在数据库中,无涯教程需要主键,id作为附加字段以及产品属性(如名称,价格等),因此,请在Product类中添加id属性。另外,添加新方法toMap将产品对象转换为Map对象。 fromMap和toMap用于对Product对象进行序列化和反序列化,并用于数据库操作方法中。

class Product { final int id; final String name; final String description; final int price; final String image; static final columns = ["id", "name", "description", "price", "image"]; Product(this.id, this.name, this.description, this.price, this.image); factory Product.fromMap(Map<String, dynamic> data) {return Product( data[id], data[name], data[description], data[price], data[image], ); } Map<String, dynamic> toMap() => {"id": id, "name": name, "description": description, "price": price, "image": image }; 
}
  • 在lib文件夹中创建一个新文件Database.dart,以编写SQLite的相关函数。

  • 在Database.dart中导入必要的import语句。

import dart:async; 
import dart:io; 
import package:path/path.dart; 
import package:path_provider/path_provider.dart; 
import package:sqflite/sqflite.dart; 
import Product.dart;
  • 请注意以下几点-

    • async                    -  用于编写异步方法。

    • io                           -  用于访问文件和目录。

    • path                      -  用于访问与文件路径相关的dart核心实用程序函数。

    • path_provider    -  用于获取临时路径和应用程序路径。

    • sqflite                   -  用于操作SQLite的数据库。

  • 创建一个新的类SQLite的DbProvider

  •     - 声明一个基于单例的静态SQLite的DbProvider对象,如下所示:

class SQLiteDbProvider { SQLiteDbProvider._(); static final SQLiteDbProvider db=SQLiteDbProvider._(); static Database _database; 
} 
  •     - 可以通过静态db变量访问SQLite的DBProvoider对象及其方法。

SQLiteDBProvoider.db.<emthod> 
  •     - 创建一个方法来获取类型为Future <Database>的数据库,创建产品表并在数据库本身创建期间加载初始数据。

Future<Database> get database async { if (_database != null) return _database; _database = await initDB(); return _database; 
}
initDB() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, "ProductDB.db"); return await openDatabase(path, version: 1,onOpen: (db) {}, onCreate: (Database db, int version) async {await db.execute("CREATE TABLE Product (""id INTEGER PRIMARY KEY,""name TEXT,""description TEXT,""price INTEGER," "image TEXT" ")"); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [1, "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png"]); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel.png"]); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [3, "Laptop", "Laptop is most productive development tool", 2000, "laptop.png"]\); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [4, "Tablet", "Laptop is most productive development tool", 1500, "tablet.png"]);await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png"]);await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png"]); }); 
}
  • 在这里,无涯教程使用了以下方法-

    •     -  getApplicationDocumentsDirectory -  返回应用程序目录路径

    •     -  join                        - 用于创建系统特定的路径,无涯教程已经使用它来创建数据库路径。

    •     -  openDatabase     - 用于打开SQLite的数据库。

    •     -  onOpen                - 用于在打开数据库时编写代码

    •     -  onCreate              - 用于在首次创建数据库时编写代码

    •     -  db.execute           - 用于执行SQL查询。它接受一个查询。如果查询具有占位符(?),则它将接受值作为第二个参数中的列表。

  • 编写getAllProducts来获取数据库中的所有产品-

Future<List<Product>> getAllProducts() async { final db = await database; List<Map> results = await db.query("Product", columns: Product.columns, orderBy: "id ASC"); List<Product> products = new List(); results.forEach((result) { Product product = Product.fromMap(result); products.add(product); }); return products; 
}
  • 编写getProductById来获取特定于 id的产品

Future<Product> getProductById(int id) async {final db = await database; var result = await db.query("Product", where: "id=", whereArgs: [id]); return result.isNotEmpty ? Product.fromMap(result.first) : Null; 
}
  • 在这里,无涯教程使用了where和whereArgs来应用过滤器。

  • 创建三种方法-插入,更新和删除方法,以从数据库中插入,更新和删除产品。

insert(Product product) async { final db = await database; var maxIdResult = await db.rawQuery("SELECT MAX(id)+1 as last_inserted_id FROM Product");var id = maxIdResult.first["last_inserted_id"]; var result = await db.rawInsert("INSERT Into Product (id, name, description, price, image)" " VALUES (?, ?, ?, ?, ?)", [id, product.name, product.description, product.price, product.image] ); return result; 
}
update(Product product) async { final db = await database; var result = await db.update("Product", product.toMap(), where: "id=?", whereArgs: [product.id]); return result; 
} 
delete(int id) async { final db = await database; db.delete("Product", where: "id=?", whereArgs: [id]); 
}
  • Database.dart的最终代码如下-

import dart:async; 
import dart:io; 
import package:path/path.dart; 
import package:path_provider/path_provider.dart; 
import package:sqflite/sqflite.dart; 
import Product.dart; class SQLiteDbProvider {SQLiteDbProvider._(); static final SQLiteDbProvider db = SQLiteDbProvider._(); static Database _database; Future<Database> get database async {if (_database != null) return _database; _database = await initDB(); return _database; } initDB() async {Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, "ProductDB.db"); return await openDatabase(path, version: 1, onOpen: (db) {}, onCreate: (Database db, int version) async {await db.execute("CREATE TABLE Product (" "id INTEGER PRIMARY KEY," "name TEXT," "description TEXT," "price INTEGER," "image TEXT"")"); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [1, "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png"]); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel.png"]);await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [3, "Laptop", "Laptop is most productive development tool", 2000, "laptop.png"]); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [4, "Tablet", "Laptop is most productive development tool", 1500, "tablet.png"]); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png"]);await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png"]); }); }Future<List<Product>> getAllProducts() async {final db = await database; List<Map> results = await db.query("Product", columns: Product.columns, orderBy: "id ASC"); List<Product> products = new List();   results.forEach((result) {Product product = Product.fromMap(result); products.add(product); }); return products; } Future<Product> getProductById(int id) async {final db = await database; var result = await db.query("Product", where: "id=", whereArgs: [id]); return result.isNotEmpty ? Product.fromMap(result.first) : Null; } insert(Product product) async { final db = await database; var maxIdResult = await db.rawQuery("SELECT MAX(id)+1 as last_inserted_id FROM Product"); var id = maxIdResult.first["last_inserted_id"]; var result = await db.rawInsert("INSERT Into Product (id, name, description, price, image)" " VALUES (?, ?, ?, ?, ?)", [id, product.name, product.description, product.price, product.image] ); return result; } update(Product product) async { final db = await database; var result = await db.update("Product", product.toMap(), where: "id=?", whereArgs: [product.id]); return result; } delete(int id) async { final db = await database; db.delete("Product", where: "id=?", whereArgs: [id]);} 
}
  • 更改主要方法以获取产品信息。

void main() {runApp(MyApp(products: SQLiteDbProvider.db.getAllProducts())); 
}
  • 在这里,无涯教程使用了getAllProducts方法来从数据库中获取所有产品。

  • 运行该应用程序并查看结果。它与先前的示例访问产品服务API相似,不同之处在于,产品信息是从本地SQLite的数据库存储和获取的。

Flutter - 数据库 - 无涯教程网无涯教程网提供SQLite" class="css-1occaib">SQLite数据库是基于事实和标准SQL的嵌入式数据库引擎...https://www.learnfk.com/flutter/flutter-database-concepts.html

相关文章:

无涯教程-Flutter - 数据库

SQLite" class"css-1occaib">SQLite数据库是基于事实和标准SQL的嵌入式数据库引擎&#xff0c;它是小型且经过时间考验的数据库引擎&#xff0c;sqflite软件包提供了许多函数&#xff0c;可以有效地与SQLite数据库一起使用&#xff0c;它提供了操作SQLite数据…...

算法笔记:平衡二叉树

1 介绍 平衡二叉树&#xff08;AVL树&#xff09;是一种特殊的二叉搜索树&#xff08;BST&#xff09;&#xff0c;它自动确保树保持低高度&#xff0c;以便实现各种基本操作&#xff08;如添加、删除和查找&#xff09;的高效性能。 ——>时间都维持在了O(logN)它是一棵空…...

redis 通用命令

目录 通用命令是什么 SET & GET keys EXISTS DEL EXPIRE TTL redis 的过期策略 定时器策略 基于优先级队列定时器 基于时间轮的定时器 TYPE 通过 redis 客户端和 redis 服务器交互。 所以需要使用 redis 的命令&#xff0c;但是 redis 的命令非常多。 通用命令…...

Pycharm配置及使用Git教程

文章目录 1. 安装PyCharm2. 安装Git3. 在PyCharm中配置Git插件4. 连接远程Gtilab仓库5. Clone项目代码6. 将本地文件提交到远程仓库6.1 git add6.2 git commit6.3 git push6.4 git pull 平时习惯在windows下开发&#xff0c;但是我们又需要实时将远方仓库的代码clone到本地&…...

CSS transition 过渡

1 前言 水平居中、垂直居中是前端面试百问不厌的问题。 其实现方案也是多种多样&#xff0c;常叫人头昏眼花。 水平方向可以认为是内联方向&#xff0c;垂直方向认为是块级方向。 下面介绍一些常见的方法。 2 内联元素的水平垂直居中 首先&#xff0c;常见内联元素有&…...

Unity中Shader的UV扭曲效果的实现

文章目录 前言一、实现的思路1、在属性面板暴露一个 扭曲贴图的属性2、在片元结构体中&#xff0c;新增一个float2类型的变量&#xff0c;用于独立存储将用于扭曲的纹理的信息3、在顶点着色器中&#xff0c;根据需要使用TRANSFORM_TEX对Tilling 和 Offset 插值&#xff1b;以及…...

Automotive 添加一个特权APP

Automotive 添加一个特权APP platform: android-13.0.0_r32 一. 添加一个自定义空调的app为例 路径&#xff1a;packages/apps/Car/MyHvac app内容可以自己定义&#xff0c;目录结构如下&#xff1a; 1.1 Android.bp package {default_applicable_licenses: ["Andr…...

自定义TimeLine

自定义TimeLine 什么是TimeLineData&#xff08;数据&#xff09;Clip&#xff08;片段&#xff09;Track&#xff08;轨道&#xff09;Mixer&#xff08;混合&#xff09; 什么是TimeLine 在 Unity 中&#xff0c;TimeLine&#xff08;时间轴&#xff09;是一种用于创建和管理…...

如何使用SQL系列 之 如何在SQL中使用WHERE条件语句

引言 在结构化查询语言 (SQL)语句中&#xff0c;WHERE子句限制了给定操作会影响哪些行。它们通过定义特定的条件(称为搜索条件)来实现这一点&#xff0c;每一行都必须满足这些条件才能受到操作的影响。 本指南将介绍WHERE子句中使用的通用语法。它还将概述如何在单个WHERE子句…...

leetcode:1941. 检查是否所有字符出现次数相同(python3解法)

难度&#xff1a;简单 给你一个字符串 s &#xff0c;如果 s 是一个 好 字符串&#xff0c;请你返回 true &#xff0c;否则请返回 false 。 如果 s 中出现过的 所有 字符的出现次数 相同 &#xff0c;那么我们称字符串 s 是 好 字符串。 示例 1&#xff1a; 输入&#xff1a;s…...

Echarts 各种点击事件监听

目录 一、鼠标事件1.1、左击1.2、双击1.3、右击1.4、右键双击1.5、中轴滚动二、时间轴2.1、时间轴监听三、拖动3.1、拖动事件一、鼠标事件 1.1、左击 chart.on(click, function(params)...

《智能网联汽车自动驾驶功能测试规程》

一、 编制背景 2018 年4 月12 日&#xff0c;工业和信息化部、公安部、交通运输部联合发布《智能网联汽车道路测试管理规范(试行)》&#xff08;以下简称《管理规范》&#xff09;&#xff0c;对智能网联汽车道路测试申请、审核、管理以及测试主体、测试驾驶人和测试车辆要求等…...

NVIDIA CUDA Win10安装步骤

前言 windows10 版本安装 CUDA &#xff0c;首先需要下载两个安装包 CUDA toolkit&#xff08;toolkit就是指工具包&#xff09;cuDNN 1. 安装前准备 在安装CUDA之前&#xff0c;需要完成以下准备工作&#xff1a; 确认你的显卡已经正确安装&#xff0c;在设备管理器中可以看…...

Elasticsearch、Kibana以及Java操作ES 的快速使用

docker 安装elastic search 、 kibana&#xff08;可视化管理elastic search&#xff09; docker pull elasticsearch:7.12.1 docker pull kibana:7.12.1创建docker自定义网络 docker自定义网络可以使得容器之间使用容器名网络互连&#xff0c;默认的网络不会有这功能。 一定…...

逐鹿人形机器人,百度、腾讯、小米卷起来

长期不温不火的人形机器人产业迎来新风口&#xff0c;技术显著提升、新品层出不穷、资本投资态度也逐渐好转。 8月18日&#xff0c;2023世界机器人大会博览会正式开放&#xff0c;全面展示了机器人行业的新技术、新产品和新应用。据悉&#xff0c;此次展会展览总面积达4.5万平…...

AndroidStudio推荐下载和配置

1、推荐下载链接 Download Android Studio & App Tools - Android Developers 2、gradle配置案例 // Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {maven { url https://maven.aliyun.…...

mysql异常占用资源排查

通过执行日志与连接信息排查 查看是否开启日志记录 mysql> show global variables like %general%; --------------------------------- | Variable_name | Value | --------------------------------- | general_log | OFF | | general_log_file…...

requests 库:发送 form-data 格式的 http 请求 (python)

安装 requests-toolbelt !pip install requests-toolbeltdemo from requests_toolbelt import MultipartEncoder import requestsm MultipartEncoder(fields{query: """第一&#xff0c;向量化匹配是有能力上限的。搜索引擎实现语义搜索已经是好几年的事情了…...

行测图形推理规律(一)元素组成

题库&#xff1a;粉笔网题库 (fenbi.com) 不知道和测评的行测题库是不是一样的&#xff0c;但是总结的规律应该是一样的。 规律并不唯一&#xff0c;题库的答案也只是参考答案&#xff0c;切勿当杠精&#xff0c;你觉得你的规律更合适就别管。本人所归纳的规律仅代表本人想法…...

【python爬虫】13.吃什么不会胖(爬虫实操练习)

文章目录 前言项目实操明确目标分析过程代码实现 前言 吃什么不会胖——这是我前段时间在健身时比较关注的话题。 相信很多人&#xff0c;哪怕不健身&#xff0c;也会和我一样注重饮食的健康&#xff0c;在乎自己每天摄入的食物热量。 不过&#xff0c;生活中应该很少有人会…...

深入理解联邦学习——联邦学习与现有理论的区别与联系

分类目录&#xff1a;《深入理解联邦学习》总目录 作为一种全新的技术&#xff0c;联邦学习在借鉴一些成熟技术的同时也具备了一定的独创性。下面我们就从多个角度来阐释联邦学习和其他相关概念之间的关系。 联邦学习与差分隐私理论的区别 联邦学习的特点使其可以被用来保护用…...

基于Python+DenseNet121算法模型实现一个图像分类识别系统案例

目录 介绍在TensorFlow中的应用实战案例最后 一、介绍 DenseNet&#xff08;Densely Connected Convolutional Networks&#xff09;是一种卷积神经网络&#xff08;CNN&#xff09;架构&#xff0c;2017年由Gao Huang等人提出。该网络的核心思想是密集连接&#xff0c;即每…...

旋转图片两种方法

这两种方法在旋转图像时&#xff0c;可能会产生一些不同的效果&#xff1a; rotate_image_new()旋转后的图像完全包含旋转前的内容&#xff0c;并且填充边界尽可能小 rotate_image() 保持原始图像的大小&#xff0c;并根据填充选项决定是否填充边界为白色。如果 if_fill_whit…...

10 mysql tiny/small/medium/big int 的数据存储

前言 这里主要是 由于之前的一个 datetime 存储的时间 导致的问题的衍生出来的探究 探究的主要内容为 int 类类型的存储, 浮点类类型的存储, char 类类型的存储, blob 类类型的存储, enum/json/set/bit 类类型的存储 本文主要 的相关内容是 int 类类型的相关数据的存储 …...

UI自动化测试之Jenkins配置

团队下半年的目标之一是实现自动化测试&#xff0c;这里要吐槽一下&#xff0c;之前开发的测试平台了&#xff0c;最初的目的是用来做接口自动化测试和性能测试&#xff0c;但由于各种原因&#xff0c;接口自动化测试那部分功能整个废弃掉了&#xff0c;其中和易用性有很大关系…...

电视盒子什么品牌好?数码博主盘点目前性能最好的电视盒子

电视盒子是非常重要的&#xff0c;老人小孩基本每天都会看电视&#xff0c;而电视盒子作为电视盒子的最佳拍档销量十分火爆&#xff0c;我自己每个月都会测评几次电视盒子&#xff0c;今天给大家详细解读一下电视盒子什么品牌好&#xff0c;看看目前性能最好的电视盒子是哪些&a…...

对于枚举类型的输出

对于枚举类型的输出 对于枚举类型的输出&#xff0c;您可以使用以下方法&#xff1a;1. 将枚举值转换为整数进行输出&#xff1a;cppODU_TYPE type ODU_TYPE_331;int value static_cast<int>(type);std::cout << "ODU_TYPE: " << value <<…...

solidity开发环境配置,vscode搭配remix

#学习笔记 初学solidity&#xff0c;使用remix非常方便&#xff0c;因为需要的环境都配置好了&#xff0c;打开网站就可以使用。 不过在编写代码方面&#xff0c;使用vscode更方便&#xff0c;而vscode本身并不能像remix那样部署合约&#xff0c;它还需要安装插件。 点击红色箭…...

chatGPT生成代码--go组合算法

提问&#xff1a;用golang写一个组合算法函数zuhe(x,n)&#xff0c;x为组合所需的字符&#xff0c;n 为组合后的字符串长度&#xff0c;例如 x"ab", n2 结果返回 aa,ab,bb,ba 结果&#xff1a;下面是一个用Go编写的生成长度为n的字符串组合的函数 zuhe&#xff0c;其…...

推荐6款普通人搞副业做自媒体AI工具

hi&#xff0c;同学们&#xff0c;我是赤辰&#xff0c;本期是赤辰第5篇AI工具类教程&#xff0c;文章底部准备了粉丝福利&#xff0c;看完可以领取&#xff01;身边越来越多的小伙伴靠自媒体实现财富自由了&#xff01;因此&#xff0c;推荐大家在工作之余或空闲时间从事自媒体…...

wordpress4.9升级失败/网络营销的推广

目录一&#xff0c;后端部署1&#xff0c;项目打包1.1&#xff0c;引入插件1.2&#xff0c;maven打包1.3&#xff0c;修改项目版本号1.4&#xff0c;验证1.5&#xff0c;生成配置文件2&#xff0c;服务器环境搭建2.1&#xff0c;安装JDK1&#xff09;下载2&#xff09;tar包安装…...

wordpress 免费插件/谈谈你对网络营销的看法

一、硬件材料 1*Arduino UNO R3开发板 1*光敏电阻 1*人体热释红外传感器 1*舵机模块 G90舵机 二、硬件接线图 CSDN 赤鱼科技...

初学者怎么做php网站/东莞网站建设推广技巧

七种办法减少Word容量(转)利用Word生成的文档&#xff0c;每页在20KB左右&#xff0c;但看到用记事本生成的文档&#xff0c;相同的内容只有1KB左右&#xff0c;能让Word也减减肥吗&#xff1f;其实我们可以采用一些行之有效的方法来减小Word文档的容量。 1&#xff0e;取消快速…...

哪个网站做衣服的/房地产营销策略有哪些

一、下载Oracle 11g R2版本。网址&#xff1a;https://www.oracle.com/index.html,下载需要登录oracle网站&#xff0c;没有账户就注册一个。或直接下载地址&#xff1a;http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html 点Downloads-->…...

wordpress 标签调用/百度热搜关键词

ORM&#xff1a;对象关系映射(Object Relational Mapping&#xff0c;简称ORM) 作用&#xff1a;根据类生成表结构&#xff0c;将对象、列表的操作转换成对象的SQL语句&#xff0c;将SQL语句查询的结果转换为对象或列表 优点&#xff1a;极大的减轻开发人员的工作量&#xff0c…...

怎样做淘宝联盟网站/google首页

在后面标注字段类型就可以了 #{id,jdbcTypeVARCHAR}...