代码之家  ›  专栏  ›  技术社区  ›  sgerbhctim

如何对特定事件执行更新?

  •  0
  • sgerbhctim  · 技术社区  · 7 年前

    我正在尝试执行一个更新:

    如果当前时间晚于拍卖结束时间(即不活动),则设置 status 表的列 auctions 0 . 否则,设置为“1”。

    rs = st.executeQuery("select * from auctions");
    System.out.println("### TESTING DATETIMES ####");
    while(rs.next()){
        Timestamp start = rs.getTimestamp("startdatetime");
        Timestamp current = Timestamp.valueOf(LocalDateTime.now().format(formatter));
        Timestamp end = rs.getTimestamp("enddatetime");
    
        int auctionID = rs.getInt("aucID");
    
        System.out.println(start);
        System.out.println(current);
        System.out.println(end);
    
        boolean inactive = current.after(end);
        System.out.println(inactive);
    
        if(current.after(end)){
            System.out.println("Inactive");
            st.executeUpdate("UPDATE auctions SET status='inactive' WHERE aucID=" + auctionID);
        }else{
            System.out.println("Active");
            st.executeUpdate("UPDATE auctions SET status='active' WHERE aucID=" + auctionID);
        } 
    }
    

    我一直在犯这个错误。。

    结果集关闭后允许

    2 回复  |  直到 7 年前
        1
  •  1
  •   Tim Biegeleisen    7 年前

    您甚至不需要在此处执行select,您可以执行单个update语句:

    UPDATE auctions
    SET status = CASE WHEN enddatetime < NOW()
                      THEN 'inactive'
                      ELSE 'active' END
    WHERE aucID = <some ID>;
    

    但是,我一般不建议使用这种方法,因为active/inactive标签是派生数据,可能不会插入。相反,您可能被迫多次运行此更新,这不是最佳的。相反,您可以随时选择此标签。

    ResultSet 在它被关闭之后。我的建议应该消除这一点,因为这样你只需要一次更新,类似这样:

    String sql = "UPDATE auctions SET status = CASE WHEN enddatetime < NOW() ";
    sql += "THEN 'inactive' ELSE 'active' END WHERE aucID = ?";
    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setInt(1, 123);
    ps.executeUpdate();
    
        2
  •  0
  •   Roshana Pitigala Laxmansinghsodhanohdiyala    7 年前

    尝试使用 executeUpdate() 使用后 ResultSet . 分配 auctionID ArrayList

    ArrayList<Integer> inactiveIDs = new ArrayList(), activeIDs = new ArrayList();
    
    while(rs.next()){
    
        ... 
    
        if(current.after(end)){
            System.out.println("Inactive");
            inactiveIDs.add(auctionID);
        }else{
            System.out.println("Active");
            activeIDs.add(auctionID);
        } 
    }
    
    for(Integer auctionID: inactiveIDs){
        st.executeUpdate("UPDATE auctions SET status='inactive' WHERE aucID=" + auctionID);
    }
    
    for(Integer auctionID: activeIDs){
        st.executeUpdate("UPDATE auctions SET status='active' WHERE aucID=" + auctionID);
    }
    
    推荐文章