Executebatch 仅在最后一行插入数据库时​​不起作用

Executebatch not working only last rows insert in database

我这样做但是在数据库最后一行只更新。

我检查了那里是否有 20 行,所有行都在 addbatch 时添加,但在 executeBatch 时,数据库中只更新了最后一行。

ArrayList<String> li = (ArrayList<String>)request.getAttribute("VL01Data");
Iterator<String> it = li.iterator();
String splitter = request.getAttribute("SPLITTER") != null ?(String)request.getAttribute("SPLITTER"): "!";                       

String QueryIn = "INSERT INTO ......) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";                   

while(it.hasNext()) {
    String value =it.next().toString(); 

    StringTokenizer strTok = new StringTokenizer(value,splitter);
    String S = strTok.nextElement().toString().trim();
    String I = strTok.nextElement().toString().trim();              
    String M = strTok.nextElement().toString().trim();
    String d = strTok.nextElement().toString();             
    String R = strTok.nextElement().toString().trim();              
    String Pu = strTok.nextElement().toString().trim();             
             .               
             .                 

    pstmt = con.prepareStatement(QueryIn);
    pstmt.setString(1,e );
    pstmt.setString(2, r);
    pstmt.setString(3, y);
    pstmt.setString(4, d);
    pstmt.setString(5, y);
    pstmt.setString(6, i);  
                 .
                 .
    pstmt.setString(19,f1 );    
    pstmt.setString(20,f2);                 
    pstmt.addBatch();                                           
}

pstmt.executeBatch();               
con.commit();           

不要重新prepare循环体中的语句。在循环之前准备一次

pstmt = con.prepareStatement(QueryIn);

while(it.hasNext()) {
  String value = it.next().toString(); 

  StringTokenizer strTok = new StringTokenizer(value,splitter);
  String S = strTok.nextElement().toString().trim();
  String I = strTok.nextElement().toString().trim();                
  String M = strTok.nextElement().toString().trim();
  String d = strTok.nextElement().toString();               
  String R = strTok.nextElement().toString().trim();                
  String Pu = strTok.nextElement().toString().trim();

  // pstmt=con.prepareStatement(QueryIn);
  // ...

当您通过调用 prepareStatement 重新分配 pstmt 引用时,它会丢失前一个(批次)状态(在每次循环迭代中),所以当您调用 executeBatch().

时,您只会得到最后一个