1

Im working on reading a .xls file (excel) and inserting it to my database. Im using a jsp to do this and it's working fine if there's no duplicate key.

    patientId = list1.get(i).toString();
    patientFname = list2.get(i).toString();
    patientLname = list3.get(i).toString();
    patientMname = list4.get(i).toString();
    patientGender = list5.get(i).toString();
    patientBirthday = list6.get(i).toString();
    patientAge = list7.get(i).toString();
    patientAddress = list8.get(i).toString();
    patientCompany = list9.get(i).toString();

ResultSet rs=st.executeQuery("SELECT idpatients FROM patients");

    if (rs.first()) {

    }
    st.executeUpdate("insert into patients(idpatients,pfirstname,plastname,pmiddlename,gender,birthdate,age,address,company) values('"+patientId+"','"+patientFname+"','"+patientLname+"','"+patientMname+"','"+patientGender+"','"+patientBirthday+"','"+patientAge+"','"+patientAddress+"','"+patientCompany+"')");

It's not working if there's a duplicate primary key and I would like to ignore that and proceed to the next data.

Ghost
  • 149
  • 1
  • 2
  • 10

4 Answers4

1

If you really want to just do nothing in the case of a duplicate key, INSERT IGNORE is right up your alley:

st.executeUpdate("insert ignore into patients(idpatients,pfirstname,plastname,pmiddlename,gender,birthdate,age,address,company) values('"+patientId+"','"+patientFname+"','"+patientLname+"','"+patientMname+"','"+patientGender+"','"+patientBirthday+"','"+patientAge+"','"+patientAddress+"','"+patientCompany+"')");
Alex Wittig
  • 2,800
  • 1
  • 33
  • 42
1

If you just want to ignore the primary key violation then you can use

INSERT IGNORE INTO patients (columns here) VALUES (values here)
Jeff
  • 908
  • 2
  • 9
  • 23
1

Use INSERT IGNORE ... or INSERT ... ON DUPLICATE KEY UPDATE. See this answer for a good reference on the differences.

Community
  • 1
  • 1
Filipe Silva
  • 21,189
  • 5
  • 53
  • 68
0

Use INSERT ... ON DUPLICATE KEY UPDATE

insert into patients(idpatients,pfirstname,plastname,pmiddlename,gender,birthdate,age,address,company) values('"+patientId+"','"+patientFname+"','"+patientLname+"','"+patientMname+"','"+patientGender+"','"+patientBirthday+"','"+patientAge+"','"+patientAddress+"','"+patientCompany+"' ON DUPLICATE KEY UPDATE idpatients=idpatients;"

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Cillier
  • 1,021
  • 9
  • 8