如何更新版本库SQFLite flutter?

x6yk4ghg  于 2023-01-21  发布在  Flutter
关注(0)|答案(4)|浏览(231)

我需要在本地数据库中创建新表并删除其他表,但是只更改数据库版本并不起作用,它不会创建我需要的新表。
以同样的方式,我已经尝试了onUpgrade,但它没有工作

Future<Database>  get database async{
    if( _database != null  )return _database;
    _database = await initDB();
    return _database;

  }

  initDB()async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join( documentDirectory.path, 'DB.db' );
     var ouDb =  await openDatabase(path, version: 2,onCreate: onCreate, onUpgrade: onUpgrade);
     return ouDb;
    }

  FutureOr<void> onCreate(Database db, int version) async {

      await db.execute('CREATE TABLE nameTable0...');


      db.execute("DROP TABLE IF EXISTS NameTable1");
      db.execute("DROP TABLE IF EXISTS NameTable2");


  }

  FutureOr<void> onUpgrade(Database db, int oldVersion, int newVersion) async{
      if (oldVersion < newVersion) {
        await db.execute('CREATE TABLE NameTable3 ...');
      }
      //onCreate(db, newVersion); 
  }
ru9i0ody

ru9i0ody1#

您需要使用onUpgrade

initDb() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, 'maindb.db');
    var ourDb = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade);
    return ourDb;
  }

  // UPGRADE DATABASE TABLES
  void _onUpgrade(Database db, int oldVersion, int newVersion) {
    if (oldVersion < newVersion) {
      // you can execute drop table and create table
      db.execute("ALTER TABLE tb_name ADD COLUMN newCol TEXT;");
    }
  }
yhived7q

yhived7q2#

我想这会帮助你...

Future<Database> openDatabase(String path,
    int version,
    {OnDatabaseConfigureFn? onConfigure,
      OnDatabaseCreateFn? onCreate,
      OnDatabaseVersionChangeFn? onUpgrade,
      OnDatabaseVersionChangeFn? onDowngrade,
      OnDatabaseOpenFn? onOpen,
      bool readOnly = false,
      bool singleInstance = true}) {
  final options = OpenDatabaseOptions(
      version: 4,
      onConfigure: onConfigure,
      onCreate: _createDb,
      onUpgrade: _upgradeDb,
      onDowngrade: onDowngrade,
      onOpen: onOpen,
      readOnly: readOnly,
      singleInstance: singleInstance);
  return databaseFactory.openDatabase(path, options: options);
}

在代码中的任何位置调用它。

hl0ma9xz

hl0ma9xz3#

尝试添加Future作为返回类型,并删除查询中的分号。

// UPGRADE DATABASE TABLES
Future _onUpgrade(Database db, int oldVersion, int newVersion) async {  
  if (oldVersion < newVersion) {
    // you can execute drop table and create table
    db.execute("ALTER TABLE tb_name ADD COLUMN newCol TEXT");
  }
}
oknrviil

oknrviil4#

我看到很多答案解释了在openDatabase中执行以下检查:

if (oldVersion < newVersion) {
      await db.execute('CREATE TABLE CUSTOMER....');
 }

这将在执行第一次数据库升级时生效(即版本1到2),但在执行第二个(比如2到3),因为表“CUSTOMER”已经创建。所以您需要逻辑来只调用一次升级。此外,您可能使用的是版本10的数据库,而用户使用的是版本5,所以您只需要处理6、7、8、9和10。下面是我为处理这些场景而构建的逻辑:

static Future<Database?> getDatabase() async {

    if (_dbInstance == null) {
      var databasesPath = await getDatabasesPath();
      String path = join(databasesPath, _databaseName);

      _dbInstance = await openDatabase(path, version: _databaseVersion,
          
      onUpgrade: (Database db, int oldVersion, int newVersion) async {
        //
        //Iterate from the current version to the latest version and execute SQL statements
        for (int version = oldVersion; version < newVersion; version++) {
          await _performDBUpgrade(db, version + 1);
        }
      }, 

      onCreate: (Database db, int newVersion) async {
        //
        //Start from version 1 to current version and create DB
        for (int version = 0; version < newVersion; version++) {
          await _performDBUpgrade(db, version + 1);
        }
      });
    }

    return _dbInstance;
  }

  //Call to upgrade the database. [upgradeToVersion] is the version of SQL statements that should be
  //executed.  A version of 1 is the initial creation of the database.   Anything higher would
  //be an upgrade of the database.  This function should be called once for every version upgrade.
  //For example, if current version is 1 and user is now performing an update and new version is
  //5, then this function should be called 4 times (from `onUpgrade`), where [upgradeToVersion] would be passed a 2, 3, 4 and 5.
  
  static Future<void> _performDBUpgrade(Database db, int upgradeToVersion) async {
    switch (upgradeToVersion) {
      //Upgrade to V1 (initial creation)
      case 1:
        await _dbUpdatesVersion_1(db);
        break;

      //Upgrades for V2
      case 2:
        //await _dbUpdatesVersion_2(db);
        break;
    }
  }

  ///Database updates for Version 1 (initial creation)
  static Future<void> _dbUpdatesVersion_1(Database db) async {
      await db.execute('CREATE TABLE Customer...)');
  }

相关问题