2016-02-19 58 views
1

我在做一個項目,該項目將讀取Excel電子表格的列的每一個單元格的內容並存儲所有這些信息在字符串的ArrayList的ArrayList,將所有之前將這些行記錄到MySQL數據庫中。插入字符串的ArrayList的ArrayList作爲記錄到MySQL數據庫

我有,提取此數據細,並返回字符串的ArrayLists的完整的ArrayList的方法。我遇到的問題是試圖將這些String ArrayList作爲記錄插入到SQL數據庫中。我在運行時遇到索引超出範圍異常。

任何人都可以請儘量解釋它是我錯了?我認爲這是我的ArrayList /循環/ JDBC /所有以前的一些認識fundemental缺陷。

public void insertData(ArrayList<ArrayList<String>> l) { 
    try { 

     String insert = "INSERT INTO 1person (ModuleNumber, ModuleTitle, School, ModuleCoordinator, NumberOfStudents, ExamCW, Courses, Blankety, Blank) VALUES (?,?,?,?,?,?,?,?,?)"; 
     PreparedStatement ps = con.prepareStatement(insert); 

     for (ArrayList<String> ar1 : l) { 
      //for(int i = 0; i < ar1.size(); i ++){ 
      //ps.setString(i+1, ar1.get(i) 
      ps.setString(1, ar1.get(0).toString()); 
      ps.setString(2, ar1.get(1).toString()); 
      ps.setString(3, ar1.get(2).toString()); 
      ps.setString(4, ar1.get(3).toString()); 
      ps.setString(5, ar1.get(4).toString()); 
      ps.setString(6, ar1.get(5).toString()); 
      ps.setString(7, ar1.get(6).toString()); 
      ps.setString(8, ar1.get(7).toString()); 
      ps.setString(9, ar1.get(8).toString()); 
      //} 

     } 
     ps.execute(); 

    } catch (Exception ex) { 
     System.out.println(ex); 
    } 
} 

回報:java.lang.IndexOutOfBoundsException:指數:8,大小:8

+1

列表規模'8'但你想從該列表中檢索'9'項目作爲'ar1.get(8)'。 – Satya

+0

你能解決這個問題嗎? – Jan

+0

是的,謝謝。回覆晚了非常抱歉。 – Dave

回答

1

你似乎只有8個值,你應該有9個(您嘗試插入9個值! )

一樣好,你只能叫​​一次 - 但你應該調用它每個刀片的行(和在INSERTUPDATE情況下調用executeUpdate()),或者你可以批量插入的,然後打電話executeBatch()

試試這樣說:

for (ArrayList<String> ar1 : l) { 
    if(line.size() != 9) {  
    System.out.println("This line only had "+line.size()+" elements - supposed to contain 9"); 
    for(String item : ar1) { 
     //Show for finding the error 
     System.out.println("- " + item); 
    } 
    } else { 
     for(int i = 0; i <9; ++i) { 
     ps.setString(i+1, ar1.get(i)); 
     } 
     //Mark this line to be added 
     ps.addBatch(); 
    }  
} 
int[] result = ps.executeBatch(); 
+0

謝謝Jan,這已經爲我清除了一些東西。現在完美的工作!許多thnaks – Dave