当前位置:网站首页>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();
}
}
}
边栏推荐
- STM32 key light
- It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
- What insurance products should be bought for the elderly?
- Oracle database knowledge points (I)
- Struct in linked list
- A-Frame虚拟现实开发入门
- 不得不会的Oracle数据库知识点(四)
- The FISCO bcos console calls the contract and reports an error does not exist
- Delete all elements with a value of Y. The values of array elements and y are entered by the main function through the keyboard.
- Self study software testing. To what extent can you go out and find a job?
猜你喜欢

Sequence list and linked list
![[C language] break and continue in switch statement](/img/ae/5967fefcf3262c9d3096e5c7d644fd.jpg)
[C language] break and continue in switch statement

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

2-redis architecture design to use scenarios - four deployment and operation modes (Part 2)

Recommendation of knowledge base management system

It is worthy of "Alibaba internal software test interview notes" from beginning to end, all of which are essence

A dichotomy of Valentine's Day

What is the potential of pocket network, which is favored by well-known investors?

Analysis and solution of lazyinitializationexception

It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
随机推荐
MySQL winter vacation self-study 2022 12 (2)
Global and Chinese markets of distributed control system (DCS) consumption 2022-2028: Research Report on technology, participants, trends, market size and share
老姜的特点
8. Go implementation of string conversion integer (ATOI) and leetcode
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
Future source code view -juc series
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
不得不会的Oracle数据库知识点(三)
Leetcode 121 best time to buy and sell stock (simple)
Eight year test old bird, some suggestions for 1-3 year programmers
[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)
机器学习基础:用 Lasso 做特征选择
On covariance of array and wildcard of generic type
Future源码一观-JUC系列
中电资讯-信贷业务数字化转型如何从星空到指尖?
Generic
A Kuan food rushed to the Shenzhen Stock Exchange: with annual sales of 1.1 billion, Hillhouse and Maotai CCB are shareholders
Print diamond pattern
Global and Chinese markets for coronary artery disease treatment devices 2022-2028: Research Report on technology, participants, trends, market size and share
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.