【问题标题】:Is there any way to add large list items in SQLite table in flutter?有什么方法可以在颤振的 SQLite 表中添加大型列表项?
【发布时间】:2020-11-27 22:53:58
【问题描述】:

我正在学习颤振,我正在制作一个在主页上有复选框列表项的应用程序。因此,用户可以检查项目并保存它们。我想使用 SQLite 数据库来保存用户检查的项目。但是,如果我有很多项目,如何创建数据库表?我应该在列中添加每个项目吗?

void _createDb(Database db, int newVersion) async {
  await db.execute('CREATE TABLE $AppTable($Id INTEGER PRIMARY KEY AUTO INCREMENT, $Item1 Integer, $Item2 Integer, : : $Itemn Integer )' ); 
}

或者有什么方法可以做到这一点?因为我有这么多列表项,我该如何为此创建数据表?建议我这样做吗?

【问题讨论】:

    标签: sqlite flutter dart


    【解决方案1】:

    首先,欢迎来到 Stack Overflow。 SQLite 适用于少量数据,是对数据库管理的一个很好的介绍。

    您应该花一些时间特别了解数据库设计和规范化,但您需要创建一个包含选项的表,另一个包含用户的表,以及第三个包含用户选择的选项的表。

    create table user (user_id integer, name varhcar, other varchar);
    
    create table options (option_id integer, display_text varchar);
    
    create table options_chosen ( user_id integer, option_id integer);
    
    insert into user values (1, 'Charles Aznavour', 'Famous French singer');
    
    insert into options values (1, 'Rock');
    insert into options values (2, 'Pop');
    insert into options values (3, 'Hip Hop');
    
    
    insert into options_chosen values (1, 2); 
    insert into options_chosen values (1, 3);
    
    

    然后您可以按如下方式访问数据:

    select usr.name, opt.display_text options_chosen
    from user usr
     inner join options_chosen chn
      on chn.user_id = usr.user_id
     inner join options opt
      on opt.option_id = chn.option_id;
    

    您可以一次将多行插入 SQLite,如下所示:

    insert into options_chosen values (1, 2), (1, 3), (2, 1), (2, 2), <...> ; 
    

    在 Dart 中,您将要使用 Batch 插入多条记录。 查看this example,根据需要修改如下:

    batch = db.batch();
    batch.rawInsert('INSERT INTO options_chosen VALUES (?, ?)', ['item1', 'item2']);
    batch.insert('options_chosen ', {'user_id': 1, 'option_id': 2});
    results = await batch.commit();
    

    【讨论】:

    • 感谢您的快速回复 LarsSkaug。但是如何将我的 100 个项目添加到表格列中?在 sqlite 中是否可能
    • 当然。我用以下补充更新了我的答案:插入 options_chosen 值 (1, 2), (1, 3), (2, 1), (2, 2), <...> ;
    • 我可以直接添加地图吗?最后,我需要一张这样的桌子。 ID - item1 - item2 ... itemn .
    • Lars Skaug,抱歉有太多问题。这是我的问题,我有一个地图,其中项目作为键,布尔值作为值。(地图(项目:真))。地图中有 100 个项目。那么我该如何为此创建一个表格。
    • 我对 Dart 不太熟悉,但你应该使用 Batch。您可以通过这种方式直接插入地图。我已经更新了我的答案,并参考了它的使用方式。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2020-11-16
    • 2020-01-28
    • 2018-05-21
    • 2020-05-25
    • 2020-06-13
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多