返回一个查询SELECT语句

时间:2013-09-11 23:36:59

标签: java sql jdbc

我试图从作者表中返回所有id ...但是没有工作...只是给我返回第一个ID ...但是如果我删除了返回并放到Print,那就给我所有的ID .. < / p>

String url = "jdbc:postgresql://localhost/testdb";
String user = "test";
String password = "test*";

try {
    con = DriverManager.getConnection(url, user, password);
    pst = con.prepareStatement("SELECT id FROM authors");
    rs = pst.executeQuery();

    while (rs.next()) {
        return rs.getInt(1);
    }

3 个答案:

答案 0 :(得分:1)

默认情况下,return语句返回返回的常量/变量的值,停止方法执行并离开方法。这在此解释:Returning a Value from a Method

要返回执行查询的所有结果,您必须将结果存储在List中,然后返回此列表:

List<Integer> idList = new ArrayList<Integer>();
//accessing to the database and executing the query...
rs = pst.executeQuery();
while (rs.next()) {
    //store the ids in the list
    idList.add(rs.getInt(1));
}
//close all the resources...
//at the bottom of your method
return idList;

答案 1 :(得分:1)

在这种情况下,返回扮演break的角色,我建议返回ResultSet并在视图中使用for或iterator进行迭代。

    while (rs.next()) {
        return rs;
    }

在视图中:

 while (nameOfYourFunction().next()) {
            System.Out.println( rs);
        }

答案 2 :(得分:0)

return终止你的方法调用,因为它表示这是该方法应该计算的值。只有您方法中的第一个return调用才能执行。因此,如果您计划从查询中获取所有结果,则应在使用它调用return之前返回所有这些ID的集合。

相关问题