Flutter本地数据库sqflite

一、 前言

sqflite是一款轻量级的数据库,用法类似于SQLite。

同时支持AndroidiOS

二、引用

sqflite

版本:^2.0.0+4

功能:数据库的操作。

地址:https://pub.dev/packages/sqflite

三、使用

使用单例模式来进行操作。

增删改都含有事务处理。

1. 模型

final _version = 1;//数据库版本号
final _databaseName = "User.db";//数据库名称
final _tableName = "user_user";//表名称
final _tableId = "id";//主键
final _tableTitle = "name";//名称
final _tableNum = "num";//大小

2. 数据库句柄

late Database _database;
Future get database async {
  String path = await getDatabasesPath() + "/$_databaseName";
  _database = await openDatabase(path, version: _version,
                                 onConfigure: (Database db){
                                   print("数据库创建前、降级前、升级前调用");
                                 },
                                 onDowngrade: (Database db, int version, int x){
                                   print("降级时调用");
                                 },
                                 onUpgrade: (Database db, int version, int x){
                                   print("升级时调用");
                                 },
                                 onCreate: (Database db, int version) async {
                                   print("创建时调用");
                                 },
                                 onOpen: (Database db) async {
                                   print("重新打开时调用");
                                   await _createTable(db, '''create table if not exists $_tableName ($_tableId integer primary key,$_tableTitle text,$_tableNum INTEGER)''');
                                 },
                                );
  return _database;
}

3. 创建表

Future _createTable(Database db, String sql) async{
  var batch = db.batch();
  batch.execute(sql);
  await batch.commit();
}

4. 打开或关闭

//打开
Future open() async{
  return await database;
}

///关闭
Future close() async {
  var db = await database;
  return db.close();
}

5. 添加数据

static Future insertData(String title, int num) async{
  Database db = await SqfLiteQueueData.internal().open();
  //1、普通添加
  //await db.rawDelete("insert or replace into $_tableName ($_tableId,$_tableTitle,$_tableNum) values (null,?,?)",[title, num]);
  //2、事务添加
  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. 根据id删除该条记录

static Future deleteData(int id) async{
  Database db = await SqfLiteQueueData.internal().open();
  //1、普通删除
  //await db.rawDelete("delete from _tableName where _tableId = ?",[id]);
  //2、事务删除
  db.transaction((txn) async{
    txn.rawDelete("delete from $_tableName where $_tableId = ?",[id]);
  });
  await db.batch().commit();

  await SqfLiteQueueData.internal().close();
}

7. 根据id更新该条记录

static Future updateData(int id,String title, int num) async{
  Database db = await SqfLiteQueueData.internal().open();
  //1、普通更新
  // await db.rawUpdate("update $_tableName set $_tableTitle =  ?,$_tableNum =  ? where $_tableId = ?",[title,num,id]);
  //2、事务更新
  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. 查询所有数据

static Future>> searchDates() async {
  Database db = await SqfLiteQueueData.internal().open();
  List> maps = await db.rawQuery("select * from $_tableName");
  print(maps);

  await SqfLiteQueueData.internal().close();
  return maps;
}

9. 删除数据库表

static Future deleteDataTable() async {
  Database db = await SqfLiteQueueData.internal().open();
  //1、普通删除
  //await db.rawDelete("drop table $_tableName");
  //2、事务删除
  db.transaction((txn) async{
    txn.rawDelete("drop table $_tableName");
  });
  await db.batch().commit();

  await SqfLiteQueueData.internal().close();
}

10. 删除数据库文件

static Future deleteDataBaseFile() async {
  await SqfLiteQueueData.internal().close();
  String path = await getDatabasesPath() + "/$_databaseName";
  File file = new File(path);
  if(await file.exists()){
    file.delete();
  }
}

四、完整代码

// ignore_for_file: camel_case_types

import 'dart:io';

import 'package:sqflite/sqflite.dart';

final _version = 1;//数据库版本号
final _databaseName = "User.db";//数据库名称
final _tableName = "user_user";//表名称
final _tableId = "id";//主键
final _tableTitle = "name";//名称
final _tableNum = "num";//大小

class SqfLiteQueueData{

  SqfLiteQueueData.internal();

  //数据库句柄
  late Database _database;
  Future get database async {
    String path = await getDatabasesPath() + "/$_databaseName";
    _database = await openDatabase(path, version: _version,
      onConfigure: (Database db){
        print("数据库创建前、降级前、升级前调用");
      },
      onDowngrade: (Database db, int version, int x){
        print("降级时调用");
      },
      onUpgrade: (Database db, int version, int x){
        print("升级时调用");
      },
      onCreate: (Database db, int version) async {
        print("创建时调用");
      },
      onOpen: (Database db) async {
        print("重新打开时调用");
        await _createTable(db, '''create table if not exists $_tableName ($_tableId integer primary key,$_tableTitle text,$_tableNum INTEGER)''');
      },
    );
    return _database;
  }

  /// 创建表
  Future _createTable(Database db, String sql) async{
    var batch = db.batch();
    batch.execute(sql);
    await batch.commit();
  }

  /// 添加数据
  static Future insertData(String title, int num) async{
    Database db = await SqfLiteQueueData.internal().open();
    //1、普通添加
    //await db.rawDelete("insert or replace into $_tableName ($_tableId,$_tableTitle,$_tableNum) values (null,?,?)",[title, num]);
    //2、事务添加
    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();
  }

  /// 根据id删除该条记录
  static Future deleteData(int id) async{
    Database db = await SqfLiteQueueData.internal().open();
    //1、普通删除
    //await db.rawDelete("delete from _tableName where _tableId = ?",[id]);
    //2、事务删除
    db.transaction((txn) async{
      txn.rawDelete("delete from $_tableName where $_tableId = ?",[id]);
    });
    await db.batch().commit();

    await SqfLiteQueueData.internal().close();
  }

  /// 根据id更新该条记录
  static Future updateData(int id,String title, int num) async{
    Database db = await SqfLiteQueueData.internal().open();
    //1、普通更新
    // await db.rawUpdate("update $_tableName set $_tableTitle =  ?,$_tableNum =  ? where $_tableId = ?",[title,num,id]);
    //2、事务更新
    db.transaction((txn) async{
      txn.rawUpdate("update $_tableName set $_tableTitle =  ?,$_tableNum =  ? where $_tableId = ?",[title,num,id]);
    });
    await db.batch().commit();

    await SqfLiteQueueData.internal().close();
  }

  /// 查询所有数据
  static Future>> searchDates() async {
    Database db = await SqfLiteQueueData.internal().open();
    List> maps = await db.rawQuery("select * from $_tableName");
    print(maps);

    await SqfLiteQueueData.internal().close();
    return maps;
  }

  //打开
  Future open() async{
    return await database;
  }

  ///关闭
  Future close() async {
    var db = await database;
    return db.close();
  }

  ///删除数据库表
  static Future deleteDataTable() async {
    Database db = await SqfLiteQueueData.internal().open();
    //1、普通删除
    //await db.rawDelete("drop table $_tableName");
    //2、事务删除
    db.transaction((txn) async{
      txn.rawDelete("drop table $_tableName");
    });
    await db.batch().commit();

    await SqfLiteQueueData.internal().close();
  }

  ///删除数据库文件
  static Future deleteDataBaseFile() async {
    await SqfLiteQueueData.internal().close();
    String path = await getDatabasesPath() + "/$_databaseName";
    File file = new File(path);
    if(await file.exists()){
      file.delete();
    }
  }
}

你可能感兴趣的:(Flutter,#,Flutter插件,数据库,flutter,sqflite)