與JDBC的連接工作正常。這是訪問數據庫表的代碼。文件名 -如何從select查詢的結果集中創建Java對象?
FlightDB.java 模式 - Flights1(flno INT,時間時間戳)
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 flight1 = new Flight();
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 flight;
}
這是頂級代碼的一部分------------文件名:Display.java
static Flight showFlights(ResultSet rs) throws SQLException {
Flight flight1 = new Flight();
AirDB.selectFlight(flight1);
// flight1.setflno(rs.getInt(1));
// flight1.settime(rs.getTimestamp(2));
System.out.println("New flight " + flight1.getflno());//OP: New flight 0
return flight1;
}
這是我班航班---- 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;
}
我得到0(德故障值)作爲我的輸出,這是不正確的。我想打印來自頂級java文件的輸出。我嘗試使用flight1 = AssignFlights1.showFlights(rs);也在FlightDB.java中。
感謝您查看此代碼。你能幫我解決這個問題嗎?謝謝。
謝謝你的迴應。對不起,但我沒有提到,我必須在這裏返回多行。 – meg
在這種情況下,將它們添加到(並返回一個)'ArrayList' –