Wijdan Wijdan - 4 months ago 11
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);
result.next();

splited = sCurrentLine.split(":");
name=splited[0];
age=splited[1];
String sql="Insert into contacts(Name,Phone) values('"+name+"','"+age+"')";
pst=con.prepareStatement(sql);

pst.executeUpdate();

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


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

}


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.

Answer

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();
        } 
    }
Comments