1

Im getting the exception:

Operation not allowed after ResultSet closed

Where am I wrong?

code:

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);
}
morels
  • 2,095
  • 17
  • 24
Shobit Mahajan
  • 362
  • 2
  • 10
  • 4
    You are using same `Statement` object twice. You need two different `Statement` Objects to execute query and update – Sanjeev Jul 08 '16 at 08:05

1 Answers1

3

As you will need two different Statement Objects to execute the query and update parts try:

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

Also consider using a PreparedStatement and using set* method to avoid potential SQL Injection

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64