• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Prevent Duplicate Data entry with SQLite

I currently have a student grade/class input program which accepts the following inputs: Student ID, First Name, Last Name, Class ID, Class Name, Grade Point, and Letter Grade.

For obvious reasons I would like to limit the user from entering Duplicate records for the same student/course (student id, class id) pair, as well as duplicate records for the same student id and first name/last name. (Two students should not be able to fill the same ID.

Currently I have a very basic method to add this data, I am looking for a method to use
insertWithOnConflict, but am struggling with implementation.

Here is my code for the add function:

Code:
add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(fname.getText().toString().trim().length()==0||
                        lname.getText().toString().trim().length()==0 || studentid.getText().toString().trim().length()==0)
                {
                    showMessage("Error", "Please enter First & Last Name and Student ID");
                    return;
                }
                db.execSQL("INSERT INTO CUSTOMER_TABLE VALUES('"+studentid.getText()+"','"+fname.getText()+"','"+lname.getText()+"','"+classid.getText()+"','"+classname.getText()+
                        "','"+pointgrade.getText()+"','"+lettergrade.getText()+"');");
                showMessage("Success", "Student Record added successfully");
                clearText();
            }
        });
 
Why not use a composite primary key (StudentId/ClassId)?
That way if you try and insert the same one twice, you'll get a constraint violation exception.
 
Why not use a composite primary key (StudentId/ClassId)?
That way if you try and insert the same one twice, you'll get a constraint violation exception.

Are you intending to ever allow the user to update the existing data or is it always a new record? If you do intend to you can always use this:

Code:
INSERT OR REPLACE INTO <TABLENAME> VALUES(<VALUES>)
 
Back
Top Bottom