You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sqflite时,AUTOINCREMENT与TIMESTAMP列的属性值设置及插入问题

问题解答

关于_id字段

因为你已经将_id设为INTEGER PRIMARY KEY AUTOINCREMENT,数据库会自动为每条新插入的记录生成唯一自增ID,插入数据时完全不需要手动传入id值:

  • 在IconList实体类中,把id定义为可选可空类型:
    class IconList {
      final int? id;
      final String iconName; // 示例业务字段
      // 其他业务属性...
    
      IconList({
        this.id, // 插入时无需赋值
        required this.iconName,
        // 其他必填参数...
      });
    }
    
  • 在DbHelper的insert方法中,构建插入Map时不包含_id字段(若后续有更新场景,可在id非空时再加入):
    Future<int> insertIcon(IconList icon) async {
      final db = await instance.database;
      return await db.insert(
        'icons',
        {
          'iconName': icon.iconName,
          // 仅添加需要手动输入的业务字段
        },
      );
    }
    

关于createdAt字段

你设置了TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,意味着插入时不指定该字段值,数据库会自动填充当前时间戳:

  • 在IconList类中,将createdAt设为可选参数:
    class IconList {
      final int? id;
      final String iconName;
      final DateTime? createdAt; // 可选参数
    
      IconList({
        this.id,
        required this.iconName,
        this.createdAt,
      });
    }
    
  • 在insert方法中,仅当手动传入createdAt时才将其加入Map,否则数据库自动使用默认值:
    Future<int> insertIcon(IconList icon) async {
      final db = await instance.database;
      final Map<String, dynamic> data = {
        'iconName': icon.iconName,
      };
      // 若传入了自定义时间,才加入Map
      if (icon.createdAt != null) {
        data['createdAt'] = icon.createdAt!.toIso8601String();
      }
      return await db.insert('icons', data);
    }
    

额外说明

  • 实体类中仍需保留id和createdAt属性,因为从数据库查询数据时,这两个字段会被返回,用于构建完整的IconList实例。
  • 若涉及更新操作,此时需要传入id值以定位目标记录;createdAt也可根据需求选择是否手动修改。

内容的提问来源于stack exchange,提问作者SugiuraY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:06:06