gpt4 book ai didi

java - 如何从选择查询的结果集中创建 Java 对象?

转载 作者:行者123 更新时间:2023-11-30 06:50:55 25 4
gpt4 key购买 nike

与 JDBC 的连接工作正常。这是访问数据库表的代码。文件名——

飞行数据库.java架构 – Flights1(flno int, time timestamp)

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 ---- 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 中也是如此。

感谢您查看这段代码。你能帮我解决这个问题吗?谢谢你。

最佳答案

您返回了错误的对象(另请参阅我的内联评论)

尝试

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;
}

另外,如果你正确地缩进了你的代码,它会更容易阅读和调试

关于java - 如何从选择查询的结果集中创建 Java 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com