2014-03-12 59 views
0

我從.csv文件導入數據庫值。但是,.csv中的最後一行實際上是某些列的總計,而我的導入器使用最後一行更新數據庫,這是不可取的。這會弄亂我稍後會用它做的查詢。請幫助我如何防止這種情況?爪哇 - 導入.csv文件數據庫 - 排除最後一排

我的我的.csv進口商代碼:

try 
{ 
    BufferedReader br=new BufferedReader(new FileReader("v.csv")); 
    String line; 
    while((line=br.readLine())!=null) 
    { 
     String[]value = line.split(","); 
     String sql = "INSERT into main ([Ticket #], Status, Priority, Department, [Account Name]) " 
       + "values ('"+value[0]+"','"+value[1]+"','"+value[2]+"','"+value[3]+"','"+value[4]+"')"; 
     System.out.println(sql); 
     PreparedStatement pst = null; 
     try 
     { 
      pst = db.prepareStatement(sql); 
      pst.executeUpdate(); 
     }finally{ 
      if(pst != null){ 
       pst.close(); 
      } 
     } 
    } 
    br.close(); 
} 
catch(Exception e) 
{ 
    JOptionPane.showMessageDialog(null, e); 
} 

回答

0

試試這個:

try 
{ 
    BufferedReader br=new BufferedReader(new FileReader("v.csv")); 
    ArrayList<String> lines = new ArrayList<String>(); 
    String line; 
    while((line=br.readLine())!=null) 
    { 
     lines.Add(line); 
    } 
    br.close(); 
    if (lines.size() > 1) { // be sure that the last row exists (prevents indexoutexception) 
     for (int i = 0; i < lines.size() - 1; i++) { // the - 1 excludes the last row 
      String[]value = lines.get(i).split(","); 
      String sql = "INSERT into main ([Ticket #], Status, Priority, Department, [Account Name]) " 
        + "values ('"+value[0]+"','"+value[1]+"','"+value[2]+"','"+value[3]+"','"+value[4]+"')"; 
      System.out.println(sql); 
      PreparedStatement pst = null; 
      try 
      { 
       pst = db.prepareStatement(sql); 
       pst.executeUpdate(); 
      } finally { 
       if(pst != null) { 
        pst.close(); 
       } 
      } 
     } 
    } 
} 
catch(Exception e) 
{ 
    JOptionPane.showMessageDialog(null, e); 
} 
0

如果可能的話,你可以使用Apache Commons IO ReversedLinesFileReader和閱讀正文之後的CSV。然後你可以跳過第一行。

0

試試這個:

try 
{ 
    BufferedReader br=new BufferedReader(new FileReader("v.csv")); 
    String line; 
    String firstFlag =true; 
    while((line=br.readLine())!=null) 
    { 
    if (!firstFlag){ 

    String sql = "INSERT into main ([Ticket #], Status, Priority, Department, [Account  Name]) " 
      + "values  ('"+value[0]+"','"+value[1]+"','"+value[2]+"','"+value[3]+"','"+value[4]+"')"; 
     System.out.println(sql); 
     PreparedStatement pst = null; 
     try 
     { 
      pst = db.prepareStatement(sql); 
      pst.executeUpdate(); 
     }finally{ 
      if(pst != null){ 
       pst.close(); 
      } 
     } 
} 
    String[]value = line.split(","); 
    firstFlag=false; 
    } 
    br.close(); 
} 
catch(Exception e) 
{ 
    JOptionPane.showMessageDialog(null, e); 
}