从文件读取时停止添加相同的数据

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

       }

我有一个方法可以从文件中读取 Phone 个联系人并将数据保存在数据库中,如果有重复的联系人,如何停止保存?并移动到下一个联系人。

一个解决方案是在您不想看到重复的字段上设置 unique constraint

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

然后捕获 SQLIntegrityConstraintViolationException

你的 while 循环会变成这样:

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

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