虽然有几条记录,但jdbc中的语句仅检索第一条记录

时间:2015-10-27 15:15:44

标签: java oracle jdbc

下面的代码迭代,while循环,并检索匹配的所有记录:

ResultSet rs3 = st.executeQuery("select id from fbprofiles where age<=(select age from fbprofiles where id="+user+") and id not in("+user+")");
        String id;
        query = "select id from fbprofiles where age<=(select age from fbprofiles where id="+user+") and id not in("+user+")";
        System.out.println(query);
        //ResultSet rs4;

        while(rs3.next())
        {
            st = con.createStatement();
            id = rs3.getString(1);
            System.out.println("id: "+id);
            /*query = "select name from fbpages where name in(select name from pagelikes_"+id+" where name not in('"+pagesLiked.toString()+"')) and category in("+category.toString()+")";
            System.out.println(query);
            rs4 = st.executeQuery(query);
            while(rs4.next())
            {
                message += "<a href="+rs4.getString(1)+".html style=\"color:black\">"+rs4.getString(1)+"</a><br>";
                pagesLiked.append(rs4.getString(1));
            }*/
        }

输出:

ID:2

ID:3

但是当我删除注释时,循环只迭代一次,结果集只包含1条记录而不是2条。

我为所有查询使用了不同的和相同的结果集,它们也只提供了1条记录的相同输出。

当我签入SQL数据库(11g)时,所有查询都正常工作。

2 个答案:

答案 0 :(得分:1)

当你在同一个语句上执行下一个查询时,你正在关闭rs。

public static void main(String[] args) throws SQLException, Exception {
        Connection con = ConnectionDefinition.getOracleConnection(); //my oracle connection
        String q1 = "select object_name from user_objects";      
        PreparedStatement ps = con.prepareCall(q1);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            ResultSet rs2 = ps.executeQuery(q1);
            if(rs.isClosed()){
                System.err.println("FRIST RS IS CLOSED");
            }
        }     
        con.close();
    }

答案 1 :(得分:0)

您不能与一个Statement同时执行多个Connection。当您执行第二个查询(使用另一个Statement)时,您关闭了当前正在迭代的Statement。获取另一个Connection,使用它来获取第二个Statement,然后使用Statement获取另一个ResultSet

相关问题