Farhana Naaz Ansari
Farhana Naaz Ansari

Reputation: 7944

Drop table and recreate if exist in sqflite flutter

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');
  }

Upvotes: 4

Views: 23948

Answers (3)

Nathalie Britan
Nathalie Britan

Reputation: 29

Maybe it's too late, but if it helps someone. To delete all rows from table use

final db = await database;
db.delete("tableName");

Strange, but if you await for the delete method result, it does not work.

Upvotes: 2

ehsaneha
ehsaneha

Reputation: 1843

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)");

}

Upvotes: 7

alextk
alextk

Reputation: 6239

Indeed your dropTable method does not seem to actually drop any table:

To delete (drop) a table:

DROP TABLE IF EXISTS my_table

To clear a table content:

DELETE FROM my_table

Upvotes: 7

Related Questions