Search code examples
dartfluttersqflite

Flutter DatabaseException(UNIQUE constraint failed)


I`m trying to insert some data into sqflite table but there is an error while executing insert query

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

and here is the Error

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]})

Thanks for any help:)


Solution

  • The table category_Table has a unique constraint field on it, the error shows that you tried to enter a value for category_id that it already exists, which violates primary key's uniqueness constraint for this field. Only one row can exist with a given ID value. So If you're trying to insert a row, be sure that your category_id have a unique value, or if you don't care about generating ids by yourself, you can add AUTOINCREMENT setting to your category_id column definition. This way it will be filled automatically and each row will have its own unique value.