删除表并重新创建(如果存在于sqflite flutter中)

时间:2019-03-07 07:42:16

标签: android dart flutter sqflite

我想在填充服务器数据(如果存在)之前删除表。

我正在尝试的查询

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

我已经尝试过类似的操作,但是什么也没发生。

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

3 个答案:

答案 0 :(得分:4)

在问题中被问到,我们需要一种删除表(如果存在)的方法,并使用sqflite软件包在flutter中重新创建它...

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

}

答案 1 :(得分:1)

也许为时已晚,但如果它可以帮助某人。 要删除表中的所有行,请使用

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

很奇怪,但是如果您等待删除方法的结果,它将不起作用。

答案 2 :(得分:0)

实际上,您的dropTable方法似乎并未删除任何表:

要删除(删除)表格:

DROP TABLE IF EXISTS my_table

要清除表格内容:

DELETE FROM my_table