【发布时间】:2014-04-22 16:59:18
【问题描述】:
为什么这段代码没有显示数据库中的所有值?
public Article searchAllArticles(){
try {
DbCnx cnx = new DbCnx();
conn = cnx.connection_a_postgresql();
String sql = "SELECT * FROM my_caisse.articles";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet resultat = preparedStatement.executeQuery();
while (resultat.next()) {
Article article =new Article();
article.setId_article(resultat.getLong("id_article"));
article.setDesi_article(resultat.getString("desi_article"));
article.setPrix_unitaire(resultat.getDouble("prix_unitaire"));
article.setStock_en_cours(resultat.getInt("stock_en_cours"));
article.setImg_article(resultat.getString("image_article"));
afficherArticles(article); //show all the values using System.out.println
return article;
//i have 5 lines in the table "my_caisse.articles" and i only have one result (only the first line)
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
【问题讨论】:
-
因为您在
while循环内调用return。在我所知道的大多数编程语言中,这将在第一个之后停止读取结果。 -
因为这就是
return语句的作用:它返回一个值。如果您返回一个值,则该方法内不会发生任何其他事情。如果你想返回多个结果,你需要返回一个集合。 -
又一个例子说明为什么正确的代码格式很重要。
-
@GordonLinoff 你知道哪些语言不那样工作?
-
@AnthonyGrist 。 . .在某些面向对象语言中定义迭代器时,可以返回一个值,然后继续执行。