简体   繁体   中英

how to update another operation with the values obtained from the result set using while loop?

Here is my java code:

public int function(String name)
{
    int i=0;

    int id=0;


    try
    {
        String get_id="SELECT id FROM table_name JOIN tbl_2 ON tbl_name.pk_id = tbl_2.fk_name_id where active_flag=1 and updated_at <= NOW() - INTERVAL 3 MINUTE";

        Statement stmt=(Statement) conn.createStatement();
        ResultSet rs = stmt.executeQuery(get_id);

        while (rs.next())
          {
             id= rs.getInt("id");

             String update="UPDATE table_name SET active_flag=NULL WHERE id="+id+"";    
             stmt.executeUpdate(update);
          }


        i=1;
    }
    catch(Exception e)
    {
         System.out.println(e);
    }


    return i;

  }

while running this, I am getting SQL Exception:

java.sql.SQLException: Operation not allowed after ResultSet closed


Please help me to perform this operation in an alternative and simple way. I just want to update the same table with the value obtained from first SQL Query, as there is n number of values in table and the value change dynamically, I used while loop. please help me to fix this. Thanks in advance.

Just rewrite the update sql statement to:

UPDATE table_name 
SET active_flag=NULL 
WHERE EXISTS
(
    SELECT 
        NULL 
    FROM 
        table_name as tbl
        JOIN tbl_2 
            ON tbl_name.pk_id = tbl_2.fk_name_id 
        where tbl.active_flag=1 
        and tbl.updated_at <= NOW() - INTERVAL 3 MINUTE
        AND tbl.id=table_name.id
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM