Jesper
Jesper

Reputation: 2814

Query returns nothing from database

I'm trying to get a car from my database using the value FK_adId. I've tried calling the method with the FK_adId value 52, and I've checked that a car with the FK_adId value 52 exists in my database. Why doesn't it get returned to me?

public Car getCar(int adId) {
    Car car = null;
    try {
        Class.forName("org.postgresql.Driver");
        if (con != null) {
            ps = con.prepareStatement("SELECT * FROM \"car\" WHERE \"FK_adId\" = ?;");
            ps.setInt(1, adId);
            rs = ps.executeQuery();
            rs.next();
            if (rs.next()) {
                car = new Car(rs.getString("brand"), rs.getString("vin"), rs.getString("condition"), rs.getInt("distanceTraveled"), rs.getInt("age"), rs.getInt("price"), rs.getInt("FK_adId"));
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return car;
}

Upvotes: 1

Views: 87

Answers (1)

dsh
dsh

Reputation: 12234

        rs.next();
   if (rs.next()) {

Call .next() once, not twice. You advance to the first row of the results, then you advance to the second. Since the query did not return two rows, you do not get the second row. You skipped the row you wanted.

Upvotes: 6

Related Questions