当前位置:网站首页>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();
}
}
}
边栏推荐
- The culprit of unrestrained consumption -- Summary
- Windos10 reinstallation system tutorial
- STM32 key light
- Makefile judge custom variables
- Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
- Sequence list and linked list
- Introduction to unity shader essentials reading notes Chapter III unity shader Foundation
- A dichotomy of Valentine's Day
- MySQL is installed as a Windows Service
- Analysis: misunderstanding of choosing WMS warehouse management system
猜你喜欢
![[C language] break and continue in switch statement](/img/ae/5967fefcf3262c9d3096e5c7d644fd.jpg)
[C language] break and continue in switch statement

功能:求5行5列矩阵的主、副对角线上元素之和。注意, 两条对角线相交的元素只加一次。例如:主函数中给出的矩阵的两条对角线的和为45。

老姜的特点
![[common error] custom IP instantiation error](/img/de/d3f90cd224274d87fcf153bb9244d7.jpg)
[common error] custom IP instantiation error

(Introduction to database system | Wang Shan) Chapter V database integrity: Exercises

Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders

【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示

Makefile judge custom variables
![[prefix and notes] prefix and introduction and use](/img/a6/a75e287ac481559d8f733e6ca3e59c.jpg)
[prefix and notes] prefix and introduction and use

It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
随机推荐
2-Redis架构设计到使用场景-四种部署运行模式(下)
Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders
[software testing] you haven't mastered these real interview questions of big companies?
Shell script three swordsman sed
Why use get/set instead of exposing properties
How to set the response description information when the response parameter in swagger is Boolean or integer
Interview script of Software Test Engineer
gslb(global server load balance)技术的一点理解
打印菱形图案
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
删除所有值为y的元素。数组元素中的值和y的值由主函数通过键盘输入。
2022 Software Test Engineer skill list, please check
中电资讯-信贷业务数字化转型如何从星空到指尖?
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
Weekly open source project recommendation plan
AI 助力艺术设计抄袭检索新突破!刘芳教授团队论文被多媒体顶级会议ACM MM录用
Software testers, how can you quickly improve your testing skills? Ten minutes to teach you
我管你什么okr还是kpi,PPT轻松交给你
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
Struct in linked list