Search code examples
javamysqlresultset

resultset.next() is showing output of first row only


So, I have something like this:

System.out.println("Enter owner's IC no. or plate no. : ");
String update = in.nextLine();

String sql = String.format("SELECT * FROM `vehicle` WHERE ic='%s' OR plate ='%s'",update,update);

ResultSet rs = stmt.executeQuery(sql);

if(rs.next()) {
    System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
    System.out.println("IC and PLate No. not found....");}

while (rs.next()) {
    regno = rs.getInt("regno");
    name = rs.getString("name");
    ic = rs.getString("ic");
    plate = rs.getString("plate");
    color = rs.getString("color");
    year = rs.getInt("year");
    make = rs.getString("make");
    model = rs.getString("model");
    capacity = rs.getDouble("capacity");
    type = rs.getString("type");
    maxload = rs.getDouble("maxload");

    System.out.println(toString());
}   

What I'm trying to do is, if data is found in the database, it will then print the following table for outputs that match.

Now, It is supposed to print out every output. But, it only prints out the first one.

I believe that the following code is the cause:

 if(rs.next()) {
    System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
    System.out.println("IC and PLate No. not found....");}

Solution

  • Use MessageFormat to format the output, and the counter to determine if empty result set, like so:

    String strFormat = "RegNo. {0}\tName {1}\tIC {2}\tPlate No. {3}\tColor {4}\tYear {5}\tMake {6}\tModel {7}\tCapacity {8}\tType {9}\tMax Load {10}");
    
    int counter = 0;
    
    while (rs.next()) {
        counter++;
    
        regno = rs.getInt("regno");
        name = rs.getString("name");
        ic = rs.getString("ic");
        plate = rs.getString("plate");
        color = rs.getString("color");
        year = rs.getInt("year");
        make = rs.getString("make");
        model = rs.getString("model");
        capacity = rs.getDouble("capacity");
        type = rs.getString("type");
        maxload = rs.getDouble("maxload");
    
        System.out.println(MessageFormat.format(strFormat, regno, name, ic, plate, color, year, make, model, capacity, type, maxload));
    }
    
    if (counter == 0) {
        System.out.println("IC and PLate No. not found....");
    }