'When searching for non-primary key in MySQL using DAO it keeps returning a null object
The first method works but the second method keeps returning a null object. I don't see any difference except that flight_no is the primary key. What went wrong and what's the rationale here?
public Flight getFlight(String flight_no) {
Flight flight=null;
try {
Connection con = getConnection();
PreparedStatement ps = con.prepareStatement("Select * from
flightInformation where flight_no=?");
ps.setString(1, flight_no);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
flight = new Flight();
flight.setFlight_no(rs.getString("flight_no"));
flight.setDeparture_date(rs.getString("departure_date"));
flight.setDeparture(rs.getString("departure"));
flight.setPrice(rs.getInt("price"));
}
con.close();
}
catch(Exception e){
e.printStackTrace();
}
return flight;
}
public Flight getFlight2(String departure_date, String departure) {
Flight flight=null;
try {
Connection con = getConnection();
PreparedStatement ps = con.prepareStatement("Select * from
flightInformation where departure_date=? and departure=?");
ps.setString(1, departure_date);
ps.setString(2, departure);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
flight = new Flight();
flight.setFlight_no(rs.getString("flight_no"));
flight.setDeparture_date(rs.getString("departure_date"));
flight.setDeparture(rs.getString("departure"));
flight.setPrice(rs.getInt("price"));
}
con.close();
}
catch(Exception e){
e.printStackTrace();
}
return flight;
}
To keep things simple I only use varchar and integer in MySQL:
create table flightinformation (flight_no varchar(6) primary
key, departure_date varchar(10), departure varchar(20), price
int);
And the bean which is nothing special:
public class Flight {
String flight_no, departure_date, departure;
int price;
The rest of the bean is just a bunch of getters and setters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
