2016-07-08 50 views
1

即時得到異常:得到錯誤「不允許操作的ResultSet關閉後,」

不允許操作的ResultSet關閉

我在哪裏錯後?

代碼:

try{ 

    Class.forName("com.mysql.jdbc.Driver"); 

    Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root"); 
    Statement s=con.createStatement(); 
    ResultSet rs1=s.executeQuery("Select * from items"); 

    while(rs1.next()) { 
     q= (q+Integer.parseInt(rs1.getString("qty"))); 
     //update items Set qty=5 where name='Maggi'; 
     s.executeUpdate("update items SET qty="+q+" WHERE name='"+value+"'"); 
    } 
}           
catch(Exception ee){ 
    System.out.println(ee); 
} 
+4

您正在使用兩次相同的'Statement'對象。你需要兩個不同的'Statement'對象來執行查詢和更新 – Sanjeev

回答

2

,你將需要兩個不同的Statement對象執行查詢和更新部分嘗試:

try{ 

    Class.forName("com.mysql.jdbc.Driver"); 

     Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");enter code here 
    Statement s=con.createStatement(); 
    ResultSet rs1=s.executeQuery("Select * from items"); 

    while(rs1.next()){ 
     q= (q+Integer.parseInt(rs1.getString("qty"))); 
     s=con.createStatement(); // <- create a new statement here 
     s.executeUpdate("update items SET qty="+q+" WHERE name='"+value+"'"); 
    } 
}           
catch(Exception ee){ 
    System.out.println(ee); 
} 
} 

也可以考慮使用PreparedStatement,並使用set*方法來避免潛在的SQL注入

+0

認真?只是代碼,沒有解釋? – GhostCat

+0

@Jägermeister - 對不起被叫走 - 要做的工作和所有。 –

相關問題