对不起: 首先,我想告诉你,我根本不是一个专业的 java 程序员,也不知道 arrayList 和迭代的所有来龙去脉。到目前为止,我已经走了很长一段路,但不知怎的,我并没有真正理解我的问题,因为我对 java 中的列表缺乏经验。
问题: 我尝试将我的sql查询结果(ResultSet(我认为这也是一个数组列表,所以我可能使用不需要的双数组列表。))放入ArrayList中,之后我尝试打印每个行进入我的控制台,但我遇到了第一行未打印的问题。
解决方案: 只要能够发生以下两件事,我就很好: 1. 将结果放入普通数组中(所以没有 ArrayList),这对我来说更容易,因为我确切地知道如何处理数组。 2.你们可以告诉我为什么第一行没有被打印
我的数据库: 我有两列,第一列是主键(ID),第二列是命令(String(Varchar),我想在获得它后执行它。
我的代码:
public List<String> getCommands(){
String sql = "SELECT * FROM query";
try {
PreparedStatement stmt = CONNECTION.prepareStatement(sql);
ResultSet results = stmt.executeQuery();
if (results.next()) {
List<String> row = new ArrayList<String>();
while(results.next()) {
row.add(results.getString(2));
}
return row;
} else {
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
List<String> results = SQL.getCommands();
if(results != null){
getLogger().info("Found at least 1 command");
for (Iterator<String> i = results.iterator(); i.hasNext();) {
String row = i.next();
getLogger().info("command: " + row);
}
}else{
getLogger().info("Can't find commands");
}
我的输出:它打印数据库中除第一行之外的所有内容。
最佳答案
看看ResultSet::next ,它说:
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
当您在 while 循环之前执行 if (results.next())
时,会跳过结果的第一行。
关于java - arraylist迭代器,不打印第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45654210/