User3
User3

Reputation: 2535

What does a query on UNIQUE INDEX return when it encounters a duplicate?

I have a database table called Details, there are three columns of interest to me here:

| _id | Name | DOB | ......| .....

I create a Unique index on the above - I want no two rows with the same Name and Birthdate:

CREATE UNIQUE INDEX _id ON Details (Name, BirthDate);

Now my problem scenario is as follows: I am reading from a file - inside a for loop - for each line in the file I am inserting a record into the above table if my insert query finds a duplicate, what does it return? I want to stop the iteration of the for loop to skip the insert statements after I find a duplicate and start at the next iteration. How do I detect this?

Following is my insert statement:

public void insert(String birthDate, String name, String daysOld, String hoursOld, String uRi, String minutesOld, String months, String seconds, String timestamP, String weeks, String years, String isAdhoc){
        //  InsertHelper ih = new InsertHelper(db, "columnTable");

        String INUP= "INSERT OR REPLACE INTO Details (BirthDate, Name, isAdhoc, daysOld, hoursOld, imageUri, minutesOld, monthsOld, secondsOld, timestamp, weeksOld, yearsOld) " +
                "values ("+"'"+birthDate+"'"+","+"'"+name+"'"+","+"'"+isAdhoc+"'"+","+"'"+daysOld+"'"+","+"'"+ hoursOld+"'"+","+"'"+ uRi+"'"+","+"'"+minutesOld+"'"+","+"'"+ months+"'"+","+"'"+ seconds+"'"+","+"'"+timestamP+"'"+","+"'"+weeks+"'"+","+"'"+years+"'"+");";  
        mDb.execSQL(INUP);
    }

Upvotes: 0

Views: 56

Answers (1)

LS_ᴅᴇᴠ
LS_ᴅᴇᴠ

Reputation: 11151

You are using INSERT OR REPLACE. Duplicate entries will replace existing ones, so no duplicates will exist and no error will happen.

You may use just INSERT or INSERT OR IGNORE, if you don't want existing entries to be replaced.

execSQL reference strongly encourages - and is a good practice for many reasons - to use insert instead.

Upvotes: 1

Related Questions