我想从select查询的结果集创建一个java对象

时间:2016-11-25 02:06:13

标签: java sql jdbc

与JDBC的连接工作正常。但我没有得到任何输出。 这是访问数据库表的代码。 文件名 - FlightDB.java

public static Flight selectFlight(Flight flight) 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();
            while(rs.next()){
                flight = Display.showFlights(rs);
            //  flight1 = new Flight();
//              flight1.setflno(rs.getInt(1));
//              flight1.settime(rs.getTimestamp(2));
            }
        }
        finally{
            closeResultSet(rs);
            closePreparedStatement(ps);
        }
        return flight;

    }

这是顶级代码的一部分------------         文件名:Display.java

static Flight showFlights(ResultSet rs) throws SQLException {
        Flight flight1 = new Flight();
//      Flight flight = new Flight(flno,time);
//      FlightDB.selectFlight(flight);
        flight1.setflno(rs.getInt(1));
        flight1.settime(rs.getTimestamp(2));
        System.out.println("New flight " + flight1.getflno());
        return flight1;
}

这是我的班级Flight ---- Flight.java

public Flight() {
            flno = 0;
             time = null;
        }
        public Flight(int flno  ,Timestamp time)
        {
            this.flno = flno;
            this.time = time;

        }
        public int getflno(){
            return flno;
        }
        public void setflno(int flno){
            this.flno = flno;
        }
        public Timestamp gettime(){
            return time;
        }
        public void settime(Timestamp time){
             this.time = time;
        }

感谢您查看此代码。我不确定我哪里出错了。能帮到我吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您的表名是Flights1 你在日志中看到任何例外吗? 你能试试吗

 ps = connection.prepareStatement(q1);
        rs = ps.executeQuery();
        while(rs.next()){
 Flight flight1 = new Flight();
 flight1.setflno(rs.getInt(1));
 flight1.settime(rs.getTimestamp(2));
 System.out.println("New flight " + flight1.getflno());}