How to check if a value already exists in the database in Android

后端 未结 3 1453
栀梦
栀梦 2020-12-19 20:01

I\'ve a database that I will populate with items after I parse a JSON response. How can I check if the values are already present in the database and prevent inserting again

3条回答
  •  时光说笑
    2020-12-19 20:44

    In your example table:

    When you create your table you can set your name as unique (if that is what you want unique) with the following (Using a SQLiteOpenHelper).

    String createPlayerTable = "create table " +
                    TIME_REPORT +
                    " (" +
                    USER_ID + " integer primary key autoincrement not null," +
                    CLIENT_NAME + " text not null," +                    
                    "UNIQUE("+CLIENT_NAME+")"+
                    ");";
    

    Then in you insert insertIntoDatabase method use

    db.insertOrThrow(TIME_REPORT, null, initialValues);
    

    instead of

    db.insert(TIME_REPORT, null, initialValues);
    

    This may throw a SQLiteConstraintException so you will have add a try/catch.

    Hope this is what you need.

提交回复
热议问题