Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java How can I correctly transform a result from a jdbc query

(Postgres 9.4) I have a simple query that returns the integer 4, I then capture that number and loop through an if statement and return an edited result. The answer should come out to be 4 min but I keep getting 4 weeks .For some reason this is not working for example this is my code

   try {
            Connection con = null;
            ResultSet rs;
        con=DB.getConnection();


           // this fire returns as an Integer 4
            PreparedStatement ps =con.prepareStatement("SELECT EXTRACT
(EPOCH FROM(last_reply-created_on)/60):: integer as fire from streams where id=65");
            rs= ps.executeQuery();


            while (rs.next()) {
             // I then put this method through
                System.err.println(difference(rs.getInt("fire")));
            }
            con.close();
            return ok();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    private static String difference(Integer i) {
String id="";
        if(i<60)
        {
         4 is obviously less than 60 but it is not working
            id= i+ " min";
        }
        if(i>=60 && i<1440)
        {
            id=i+ " hrs";
        }
        if(i>=1441 && i<10080)
        {
            id=i+" days";
        }
        else
        {
            id=i+" weeks";
        }
// returns as 4 date
        return id;
    }

I am using this System.err.println(difference(rs.getInt("fire"))); to track the results. How can I make this work or is there a better way to achieve this?

like image 454
Ignacio Perez Avatar asked Feb 12 '26 10:02

Ignacio Perez


1 Answers

You have a bug in if-else statement. Try below one

try {
        Connection con = null;
        ResultSet rs;
    con=DB.getConnection();


       // this fire returns as an Integer 4
        PreparedStatement ps =con.prepareStatement("SELECT EXTRACT
(EPOCH FROM(last_reply-created_on)/60):: integer as fire from streams where id=65");
        rs= ps.executeQuery();


        while (rs.next()) {
         // I then put this method through
            System.err.println(difference(rs.getInt("fire")));
        }
        con.close();
        return ok();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
private static String difference(Integer i) {
String id="";
    if(i<60)
    {
     4 is obviously less than 60 but it is not working
        id= i+ " min";
    }else if(i>=60 && i<1440)
    {
        id=i+ " hrs";
    }else if(i>=1441 && i<10080)
    {
        id=i+" days";
    }
    else
    {
        id=i+" weeks";
    }
// returns as 4 date
    return id;
}
like image 81
iCurious Avatar answered Feb 14 '26 00:02

iCurious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!