简体   繁体   中英

Statement in jdbc retrieving only the 1st record though there are several records

The below code iterates, while loop, and retrieves all the records that are matched:

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));
            }*/
        }

output:

id:2

id:3

But when I remove the comments, the loop is iterated only once, the resultset contains only 1 record instead of 2.

I have used different and sameresultsets for all the queries, which has also gave the same output with only 1 record.

All the queries are working 5n when I have checked in SQL database(11g).

You are closing rs when you execute next query on the same statement.

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();
    }

You can't execute more than one Statement simultaneously with one Connection . When you execute the second query (with another Statement ) you close the Statement that you're currently iterating. Get another Connection , use it to get your second Statement and then you use that Statement to get another ResultSet .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM