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

时间:2016-07-09 16:44:01

标签: java database string bufferedreader

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

       }

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

1 个答案:

答案 0 :(得分:0)

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

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

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

然后捕获SQLIntegrityConstraintViolationException

Yout while while会变成类似:

IsRequest BIT(1)