How do I create a Java object from the resultset of a select query?

前端 未结 2 1756
眼角桃花
眼角桃花 2021-01-23 02:12

Connection to JDBC is working fine. This is the code which accesses database tables. File name –

FlightDB.java Schema – Flights1(flno int, time timestamp)



        
相关标签:
2条回答
  • 2021-01-23 02:26

    You should return flight1 object not flight as shown below:

    public static Flight selectFlight() throws SQLException{
        PreparedStatement ps = null;
        ResultSet rs = null;
        String q1 = "Select * from Flights1 f order by f.time";
        Flight flight1 = null;
    try{
        ps = connection.prepareStatement(q1);
        rs = ps.executeQuery();
        if(rs.next()){
            flight1 = new Flight();
            flight1.setflno(rs.getInt(1));
            flight1.settime(rs.getTimestamp(2));
            // System.out.println(“new flight:” +flight1.getflno()); Correct output printed here
            }
        }
    finally{
        closeResultSet(rs);
        closePreparedStatement(ps);
    }
        return flight1;
    }
    

    Also, DO NOT use while for single record, rather use if for single record.

    0 讨论(0)
  • 2021-01-23 02:32

    You are returning the wrong Object (also see my inline comments)

    try

    public static Flight selectFlight() throws SQLException{  // no param needed
      PreparedStatement ps = null;
      ResultSet rs = null;
    
      // I guess that this will not be the query you want in the end
      String q1 = "Select * from Flights1 f order by f.time";        
      Flight flight1 = null;
      try{
        ps = connection.prepareStatement(q1);
        rs = ps.executeQuery();
        if (rs.next()){  // only returning one object so no needed for while
          flight1 = new Flight();
          flight1.setflno(rs.getInt(1));
          flight1.settime(rs.getTimestamp(2));
          System.out.println(“new flight:” +flight1.getflno()); Correct output printed here
        }
      }
      finally{
        closeResultSet(rs);
        closePreparedStatement(ps);
      }
      return flight1;
    }
    

    Also if you correctly indent your code it is alot easier to read and debug

    0 讨论(0)
提交回复
热议问题