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

前端 未结 2 1778
眼角桃花
眼角桃花 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: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

提交回复
热议问题