Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
  }
like image 555
Farhana Naaz Ansari Avatar asked Oct 16 '25 07:10

Farhana Naaz Ansari


2 Answers

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
like image 181
alextk Avatar answered Oct 17 '25 20:10

alextk


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

}
like image 29
ehsaneha Avatar answered Oct 17 '25 21:10

ehsaneha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!