Wijdan Wijdan - 7 months ago 21
Java Question

Stopping same data to be added while reading from a file

public static void getContacts() throws SQLException{
String[] splited=null;
BufferedReader br = null;

try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Wijdan\\Desktop\\2016_07_09.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String checkSql = "select count(*) from contacts where Name = '"+name+"' and Phone='"+age+"'";

Statement st = con.createStatement();
ResultSet result = st.executeQuery(checkSql);

splited = sCurrentLine.split(":");
String sql="Insert into contacts(Name,Phone) values('"+name+"','"+age+"')";


String pp=splited[0];
String pp1=splited[1];

} catch (IOException e) {
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {


I have a method which reads Phone contacts from a file and saves data in database, how to stop repeating contacts from saving if there are some? and move to the next contact.


One solution would be to set a unique constraint on the field you don't want to see duplicated

ALTER TABLE contacts
ADD CONSTRAINT contact_unique_name_phone UNIQUE (Name,Phone)

Then catching SQLIntegrityConstraintViolationException

Yout while loop would become something like:

    while ((sCurrentLine = br.readLine()) != null) {
        try {
        // your code

        } catch(SQLIntegrityConstraintViolationException e){
            sCurrentLine = br.readLine();