问题描述
所以我有一个SQL查询,该查询返回多行和多列信息,但是在textArea中显示多于一行时遇到了麻烦。下面的代码正确显示了第一行信息,但是我不确定如何才能显示其他四行信息。
String sql4 = "SELECT * FROM CarDescription JOIN LotCarList ON CarDescription.CarId = LotCarList.CarId JOIN CarLots ON LotCarList.LotId = CarLots.LotId JOIN MakeModel ON CarDescription.MId = MakeModel.MId";
PreparedStatement pstmt = con.prepareStatement(sql4);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
int carid = rs.getInt(n);
n++;
int mid = rs.getInt(n);
n++;
String color = rs.getString(n);
n++;
int mileage = rs.getInt(n);
n++;
int Price = rs.getInt(n);
n++;
int listid = rs.getInt(n);
n++;
int lotid = rs.getInt(n);
n++;
int carid2 = rs.getInt(n);
n++;
int lotid2 = rs.getInt(n);
n++;
String lotname = rs.getString(n);
n++;
String lotadd = rs.getString(n);
n++;
int mid2 = rs.getInt(n);
n++;
String make = rs.getString(n);
n++;
String model = rs.getString(n);
textArea.append(" CarID: "+carid + "\n " + "MakeID: " + mid + "\n " + "Color "+ color + "\n " + "mileage " + mileage + "\n " + "Price " + Price + "\n " + "ListId: "+ listid + "\n" + "LotId: "+ lotid + "\n" + "CarId2: "+ carid2 + "\n" + "lotid2: "+ lotid2 + "\n" + "Lotname: "+ lotname + "\n" + "Lotadd: "+ lotadd + "\n" + "Mid2: "+ mid2 + "\n" + "Make: "+ make + "\n" + "Model: "+ model + "\n");
这是SQL命令返回的内容 (https://imgur.com/a/odkoCpr)
文本区域仅显示第一行 (https://imgur.com/a/mNHf9nZ)
解决方法
您在同一while循环中使用carid2,这意味着光标仍在记录编号1处。此代码不正确。您可以执行一些操作,例如在字符串生成器中设置所有值,最后为它附加更多记录。
StringBuilder sb = new StringBuilder();
while(rs.next()) {
int carid = rs.getInt(n);
n++;
int mid = rs.getInt(n);
n++;
String color = rs.getString(n);
n++;
int mileage = rs.getInt(n);
n++;
int Price = rs.getInt(n);
n++;
int listid = rs.getInt(n);
n++;
int lotid = rs.getInt(n);
n++;
sb.append("CarID : "+carid);
sb.append("\n");
..
...
...
sb.append("Lot ID:"+lotid);
sb.append("\n");
n=0;
}
textArea.append(sb.toString());