Drop table and recreate if exist in sqflite flutter

Farhana Naaz Ansari picture Farhana Naaz Ansari · Mar 7, 2019 · Viewed 8.9k times · Source

I want to drop table before populating with server data if exist.

the Queries I'm trying

 deleteOptionTable() async {
    final db = await database;
    db.rawDelete("Delete * from option");
  }
  dropTable() async {
    final db = await database;
    db.query('SELECT * FROM cloudnet360.db WHERE name =option and type=table');
  }

I have tried something like this but nothing is happening.

void _insertOption(OptionsGroupList option) async {

    int idd =  dbHelper.dropTable();

    print('DROP TABLE: $idd');

    PreferencesConnector myprefs= PreferencesConnector();
    String merchantid=await myprefs.readString('merchantid');
    String hashkey=await myprefs.readString('hashkey');

    Map<String, dynamic> row = {
      DatabaseHelper.columnGroupId:option.grouprowid ,
      DatabaseHelper.columnGroupName: option.groupname,
      DatabaseHelper.columnIsRequired:option.isrequired ,
      DatabaseHelper.columnMerchantId: merchantid,
      DatabaseHelper.columnMerchantHashKey: hashkey,
    };
    int id = await dbHelper.insertOption(row);

    print('inserted option row id: $id');
  }

Answer

ehsaneha picture ehsaneha · Apr 6, 2020

As being asked in the question we need a method to drop a table if exists and the recreate it in flutter and by using sqflite package...

Future<void> DropTableIfExistsThenReCreate() async {

    //here we get the Database object by calling the openDatabase method 
    //which receives the path and onCreate function and all the good stuff
    Database db = await openDatabase(path,onCreate: ...);

    //here we execute a query to drop the table if exists which is called "tableName"
    //and could be given as method's input parameter too
    await db.execute("DROP TABLE IF EXISTS tableName");

    //and finally here we recreate our beloved "tableName" again which needs
    //some columns initialization
    await db.execute("CREATE TABLE tableName (id INTEGER, name TEXT)");

}