Flutter--关于Sqflite 数据库版本升级.(onUpgrade sqflite in Flutter)

整的数据库需要版本升级,新增字段.
上次整这个也是各种网上搜索
这次还是,不过感觉都不怎么优雅
直到我看到了这个…

https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md

Flutter Sqflite 数据库升级.

直接上代码吧.

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper.internal();

  factory DatabaseHelper() => _instance;
  final String tableName = "table_cart";
  final String columnId = "id";
  final String columnGoodsId = "goodsId";
  final String columnGoodsName = "goodsName";
  final String columnCount = "count";
  final String columnPrice = "price";
  final String columnImages = "images";
  final String columnOldPrice = "oldPrice";
  final String columnIsSelect = "isSelect";
  static Database _db;

  Future get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  DatabaseHelper.internal();

  initDb() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'eshop.db');
    var ourDb = await openDatabase(path,
        version: 2,
        onCreate: _onCreate,
        onUpgrade: _onUpgrade,
        onDowngrade: onDatabaseDowngradeDelete);
    return ourDb;
  }

  //创建数据库表
  void _onCreate(Database db, int version) async {
    var batch = db.batch();
    _createTableCompanyV1(batch);
    _updateTableCompanyV1toV2(batch);

    await batch.commit();
    print("Table is created");
  }

  void _onUpgrade(Database db, int oldVersion, int newVersion) async {
    var batch = db.batch();
    if (oldVersion == 1) {
      _updateTableCompanyV1toV2(batch);
    }
    await batch.commit();
  }

  ///创建数据库--初始版本
  void _createTableCompanyV1(Batch batch) {
    batch.execute(
      "CREATE TABLE $tableName($columnId INTEGER PRIMARY KEY,$columnGoodsId TEXT,$columnGoodsName TEXT, $columnCount INTEGER,$columnPrice REAL,$columnImages TEXT,$columnOldPrice REAL)",
    );
  }

  ///更新数据库Version: 1->2.
  void _updateTableCompanyV1toV2(Batch batch) {
    batch.execute('ALTER TABLE $tableName ADD $columnIsSelect BOOL');
  }
}

省略掉了 增删查改的代码,只保留了 创建数据库,升级数据库的代码逻辑.


Sqflite使用新姿势:

参照引用的example的代码,对原代码进行了修改.
将onCreate,onUpgrade 的内容进行拆分.

拆分成:
Version 1 : _createTableCompanyV1
Version 1 => 2 : _updateTableCompanyV1toV2

后续版本升级,都进行独立拆分,独立管理.
还是这样优雅一点,看着舒服一点…

你可能感兴趣的:(Flutter)