【问题标题】:Flutter DatabaseException(UNIQUE constraint failed)Flutter DatabaseException(唯一约束失败)
【发布时间】:2019-05-08 18:06:43
【问题描述】:

我正在尝试向 sqflite 表中插入一些数据,但执行插入查询时出错

await db.execute(
      'CREATE TABLE $catrgoryTable($category_id INTEGER PRIMARY KEY UNIQUE  , $colDeviceTypeId INTEGER, '
                '$room_id INTEGER)');
        print('category created!');

这是错误

SqfliteDatabaseException (DatabaseException(UNIQUE constraint failed: category_Table.category_id (code 1555)) sql 'INSERT INTO category_Table (category_id, device_type_id, room_id) VALUES (?, ?, ?)' args [1, 1, 1]})

感谢您的帮助:)

【问题讨论】:

    标签: dart flutter sqflite


    【解决方案1】:

    category_Table上有一个唯一约束字段,错误显示你试图为category_id输入一个已经存在的值,这违反了主键对该字段的唯一性约束。给定 ID 值只能存在一行。因此,如果您尝试插入一行,请确保您的 category_id 具有唯一值,或者如果您不关心自己生成 id,您可以将 AUTOINCREMENT 设置添加到您的 category_id 列定义.这样它将自动填充,并且每一行都有自己的唯一值。

    【讨论】:

      【解决方案2】:
      static Future<void> insert(String table, Map<String, dynamic> data) async {
        final db = await DBHelper.database();
        db.insert(table, data, conflictAlgorithm: sql.ConflictAlgorithm.replace);
      }
      

      这是我的代码,如果我使用冲突算法替换它会替换那个唯一值?

      【讨论】:

        【解决方案3】:

        在数据库的插入函数中。添加

        conflictAlgorithm: ConflictAlgorithm.replace.
        

        它对我有用

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-28
          • 2020-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多