【问题标题】:Flutter: Effective way of inserting list of data in databaseFlutter:在数据库中插入数据列表的有效方法
【发布时间】:2019-09-24 07:05:16
【问题描述】:

我有cities 表并在创建数据库时尝试插入城市。表结构非常简单,只有idname 列。

在我的数据库类的onCreate 方法中,我使用以下命令创建表:

var tblCities = 'cities';
await db.execute('CREATE TABLE $tblCities (id INTEGER PRIMARY KEY, name TEXT)');

我有 Cities 具有 fromMaptoMap 方法的模型类。

大约有 350 个城市,我想将它们插入表格中。

问。最好和最简单的方法是什么?

我想到了这个:

  1. 创建城市列表
  2. 使用for循环迭代整个列表
  3. 使用toMap方法创建城市地图
  4. 在循环内调用db.insert方法

我不确定,但这种方法看起来很愚蠢,所以考虑更好和优化的解决方案......

【问题讨论】:

  • 所以我应该使用rawInsert?如果是这样,那我会通过什么? (MapList
  • 不,你可以使用“普通”insert,为什么要使用rawInsert
  • 我在想也许rawInsert 是插入批量数据。
  • 感谢@pskink 的帮助,我能够通过遵循答案使其工作。

标签: flutter dart bulkinsert sqflite


【解决方案1】:

正如@chunhunghan 所说,您可以使用批处理来插入批量数据。

以下是分步指南:

  1. 准备好您的 json 文件,例如 cities.json(创建数据的 csv 文件并使用 csv 到 json 转换器,如 this
  2. 在您的assets 目录中添加cities.json 文件
  3. 像这样在pubspec.yaml 中定义它:

    assets:
     - assets/cities.json
    
  4. 将此代码粘贴到您的数据库类的onCreate 方法中(确保其在创建表后查询)

    Batch batch = db.batch();
    
    String citiesJson = await rootBundle.loadString('assets/json/cities.json');
    List citiesList = json.decode(citiesJson);
    
    
    citiesList.forEach((val) {
      //assuming you have 'Cities' class defined
      Cities city = Cities.fromMap(val);
      batch.insert(tblCities, city.toMap());
    });
    
    batch.commit();
    

就是这样! :)

【讨论】:

  • 非常感谢您的回答,您能看看this吗?
【解决方案2】:

有批处理支持
为了避免 dart 和本机代码之间的乒乓,你可以使用 Batch:

batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();

官方例子https://github.com/tekartik/sqflite/blob/master/sqflite/example/lib/batch_test_page.dart

在您的情况下,使用 batch.insert 命令的 for 循环列表更容易维护
为了语法简单,使用toMap,例子

batch.insert("cities", city.toMap());   

详情https://www.techiediaries.com/flutter-sqlite-crud-tutorial/

如果您更喜欢 rawInsert,请参考Insert multiple records in Sqflite

【讨论】:

【解决方案3】:

您可以编写一个原始查询将所有数据一次插入数据库。

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2019-09-29
    • 2012-12-13
    • 2016-02-03
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多