resultset.next()仅显示第一行的输出

问题描述 投票:1回答:2

所以,我有这样的事情:

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

我要做的是,如果在数据库中找到数据,它将打印下表以查找匹配的输出。

现在,它应该打印出每个输出。但是,它只打印出第一个。

我相信以下代码是原因:

 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....");}
java mysql resultset
2个回答
0
投票

使用MessageFormat格式化输出,使用counter确定是否为空结果集,如下所示:

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....");
}

0
投票

所以我在这里看到两个问题。最大的一个是:

System.out.println(toString());

这会调用当前类的.toString()方法,该方法不会输出ResultSet中的任何数据。至少,不是基于您展示的任何代码。您将从ResultSet返回的所有值存储在变量中,但这些变量似乎并未在任何地方使用。你需要以某种方式将这些变量带到你的.println()

第二个问题是rs.next()将光标向前移动一行。所以当你这样做时:

if(rs.next()) {

这会导致您跳过第一行。这实际上很难解决,因为没有调用ResultSet就没有好的方法来判断.next()是否为空。我可能处理的方法是将所有结果拉入列表中的对象,然后根据列表进行所有打印,而不是ResultSet本身。

© www.soinside.com 2019 - 2024. All rights reserved.