当前位置:网站首页>Flutter local database sqflite
Flutter local database sqflite
2022-07-04 00:47:00 【Leaning cloud crane】
One 、 Preface
sqflite Is a lightweight database , The usage is similar to SQLite.
Support at the same time Android
and iOS
Two 、 quote
sqflite
edition :^2.0.0+4
function : Operation of database .
Address :https://pub.dev/packages/sqflite
3、 ... and 、 Use
Use singleton mode to operate .
Adding, deleting and modifying all contain transactions .
1. Model
final _version = 1;// Database version number
final _databaseName = "User.db";// Database name
final _tableName = "user_user";// The name of the table
final _tableId = "id";// Primary key
final _tableTitle = "name";// name
final _tableNum = "num";// size
2. Database handle
late Database _database;
Future<Database> get database async {
String path = await getDatabasesPath() + "/$_databaseName";
_database = await openDatabase(path, version: _version,
onConfigure: (Database db){
print(" Before database creation 、 Before degradation 、 Call before upgrading ");
},
onDowngrade: (Database db, int version, int x){
print(" Call when demoting ");
},
onUpgrade: (Database db, int version, int x){
print(" Call when upgrading ");
},
onCreate: (Database db, int version) async {
print(" Call... On creation ");
},
onOpen: (Database db) async {
print(" Called when reopening ");
await _createTable(db, '''create table if not exists $_tableName ($_tableId integer primary key,$_tableTitle text,$_tableNum INTEGER)''');
},
);
return _database;
}
3. Create table
Future<void> _createTable(Database db, String sql) async{
var batch = db.batch();
batch.execute(sql);
await batch.commit();
}
4. Turn on or off
// open
Future<Database> open() async{
return await database;
}
/// close
Future<void> close() async {
var db = await database;
return db.close();
}
5. Add data
static Future insertData(String title, int num) async{
Database db = await SqfLiteQueueData.internal().open();
//1、 Ordinary addition
//await db.rawDelete("insert or replace into $_tableName ($_tableId,$_tableTitle,$_tableNum) values (null,?,?)",[title, num]);
//2、 Transaction add
db.transaction((txn) async{
await txn.rawInsert("insert or replace into $_tableName ($_tableId,$_tableTitle,$_tableNum) values (null,?,?)",[title, num]);
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
6. according to id Delete this record
static Future deleteData(int id) async{
Database db = await SqfLiteQueueData.internal().open();
//1、 General deletion
//await db.rawDelete("delete from _tableName where _tableId = ?",[id]);
//2、 Transaction deletion
db.transaction((txn) async{
txn.rawDelete("delete from $_tableName where $_tableId = ?",[id]);
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
7. according to id Update this record
static Future updateData(int id,String title, int num) async{
Database db = await SqfLiteQueueData.internal().open();
//1、 General update
// await db.rawUpdate("update $_tableName set $_tableTitle = ?,$_tableNum = ? where $_tableId = ?",[title,num,id]);
//2、 Transaction update
db.transaction((txn) async{
txn.rawUpdate("update $_tableName set $_tableTitle = ?,$_tableNum = ? where $_tableId = ?",[title,num,id]);
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
8. Query all the data
static Future<List<Map<String, dynamic>>> searchDates() async {
Database db = await SqfLiteQueueData.internal().open();
List<Map<String, dynamic>> maps = await db.rawQuery("select * from $_tableName");
print(maps);
await SqfLiteQueueData.internal().close();
return maps;
}
9. Delete database tables
static Future<void> deleteDataTable() async {
Database db = await SqfLiteQueueData.internal().open();
//1、 General deletion
//await db.rawDelete("drop table $_tableName");
//2、 Transaction deletion
db.transaction((txn) async{
txn.rawDelete("drop table $_tableName");
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
10. Delete database file
static Future<void> deleteDataBaseFile() async {
await SqfLiteQueueData.internal().close();
String path = await getDatabasesPath() + "/$_databaseName";
File file = new File(path);
if(await file.exists()){
file.delete();
}
}
Four 、 Complete code
// ignore_for_file: camel_case_types
import 'dart:io';
import 'package:sqflite/sqflite.dart';
final _version = 1;// Database version number
final _databaseName = "User.db";// Database name
final _tableName = "user_user";// The name of the table
final _tableId = "id";// Primary key
final _tableTitle = "name";// name
final _tableNum = "num";// size
class SqfLiteQueueData{
SqfLiteQueueData.internal();
// Database handle
late Database _database;
Future<Database> get database async {
String path = await getDatabasesPath() + "/$_databaseName";
_database = await openDatabase(path, version: _version,
onConfigure: (Database db){
print(" Before database creation 、 Before degradation 、 Call before upgrading ");
},
onDowngrade: (Database db, int version, int x){
print(" Call when demoting ");
},
onUpgrade: (Database db, int version, int x){
print(" Call when upgrading ");
},
onCreate: (Database db, int version) async {
print(" Call... On creation ");
},
onOpen: (Database db) async {
print(" Called when reopening ");
await _createTable(db, '''create table if not exists $_tableName ($_tableId integer primary key,$_tableTitle text,$_tableNum INTEGER)''');
},
);
return _database;
}
/// Create table
Future<void> _createTable(Database db, String sql) async{
var batch = db.batch();
batch.execute(sql);
await batch.commit();
}
/// Add data
static Future insertData(String title, int num) async{
Database db = await SqfLiteQueueData.internal().open();
//1、 Ordinary addition
//await db.rawDelete("insert or replace into $_tableName ($_tableId,$_tableTitle,$_tableNum) values (null,?,?)",[title, num]);
//2、 Transaction add
db.transaction((txn) async{
await txn.rawInsert("insert or replace into $_tableName ($_tableId,$_tableTitle,$_tableNum) values (null,?,?)",[title, num]);
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
/// according to id Delete this record
static Future deleteData(int id) async{
Database db = await SqfLiteQueueData.internal().open();
//1、 General deletion
//await db.rawDelete("delete from _tableName where _tableId = ?",[id]);
//2、 Transaction deletion
db.transaction((txn) async{
txn.rawDelete("delete from $_tableName where $_tableId = ?",[id]);
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
/// according to id Update this record
static Future updateData(int id,String title, int num) async{
Database db = await SqfLiteQueueData.internal().open();
//1、 General update
// await db.rawUpdate("update $_tableName set $_tableTitle = ?,$_tableNum = ? where $_tableId = ?",[title,num,id]);
//2、 Transaction update
db.transaction((txn) async{
txn.rawUpdate("update $_tableName set $_tableTitle = ?,$_tableNum = ? where $_tableId = ?",[title,num,id]);
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
/// Query all the data
static Future<List<Map<String, dynamic>>> searchDates() async {
Database db = await SqfLiteQueueData.internal().open();
List<Map<String, dynamic>> maps = await db.rawQuery("select * from $_tableName");
print(maps);
await SqfLiteQueueData.internal().close();
return maps;
}
// open
Future<Database> open() async{
return await database;
}
/// close
Future<void> close() async {
var db = await database;
return db.close();
}
/// Delete database tables
static Future<void> deleteDataTable() async {
Database db = await SqfLiteQueueData.internal().open();
//1、 General deletion
//await db.rawDelete("drop table $_tableName");
//2、 Transaction deletion
db.transaction((txn) async{
txn.rawDelete("drop table $_tableName");
});
await db.batch().commit();
await SqfLiteQueueData.internal().close();
}
/// Delete database file
static Future<void> deleteDataBaseFile() async {
await SqfLiteQueueData.internal().close();
String path = await getDatabasesPath() + "/$_databaseName";
File file = new File(path);
if(await file.exists()){
file.delete();
}
}
}
边栏推荐
- CesiumJS 2022^ 源码解读[8] - 资源封装与多线程
- From functional testing to automated testing, how did I successfully transform my salary to 15K +?
- 1-Redis架构设计到使用场景-四种部署运行模式(上)
- It is worthy of "Alibaba internal software test interview notes" from beginning to end, all of which are essence
- Is the account opening of Guoyuan securities really safe and reliable
- 我管你什么okr还是kpi,PPT轻松交给你
- Day05 表格
- PMP 考试常见工具与技术点总结
- gslb(global server load balance)技术的一点理解
- The culprit of unrestrained consumption -- Summary
猜你喜欢
[error record] configure NDK header file path in Visual Studio (three header file paths of NDK | ASM header file path selection related to CPU architecture)
[common error] custom IP instantiation error
我管你什么okr还是kpi,PPT轻松交给你
Sequence list and linked list
功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
Analysis and solution of lazyinitializationexception
What is regression testing? Talk about regression testing in the eyes of Ali Test Engineers
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
[complimentary ppt] kubemeet Chengdu review: make the delivery and management of cloud native applications easier!
GUI 应用:socket 网络聊天室
随机推荐
AI 助力艺术设计抄袭检索新突破!刘芳教授团队论文被多媒体顶级会议ACM MM录用
数据库表外键的设计
Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
Sorry, Tencent I also refused
What insurance products should be bought for the elderly?
Speed up the energy Internet of things. What can low-power Internet of things technology represented by Zeta do?
Solution to the impact of Remote Code Execution Vulnerability of log4j2 component on December 9, 2021
Function: find the approximate value of the limit of the ratio of the former term to the latter term of Fibonacci sequence. For example, when the error is 0.0001, the function value is 0.618056.
Struct in linked list
MySQL winter vacation self-study 2022 12 (2)
1-Redis架构设计到使用场景-四种部署运行模式(上)
Introduction to A-frame virtual reality development
Oracle database knowledge points (I)
What are the application fields of digital twins in industry?
All in one 1407: stupid monkey
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
Eight year test old bird, some suggestions for 1-3 year programmers
Print diamond pattern
功能:求5行5列矩阵的主、副对角线上元素之和。注意, 两条对角线相交的元素只加一次。例如:主函数中给出的矩阵的两条对角线的和为45。
STM32 key light