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

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

提交回复
热议问题