ResultSet is false in executeQuery Mysql - Java even when row exist

1.5k Views Asked by At

I am fetching two columns from a table in MySql using preparedStatement in Java.The query is valid and returns rows if I execute it on mySql DB directly. but for this method call, ResultSet has values "false" on each ResultSet.next() call. Below is the code:

private ResultSet fetchFriends(int lActProfId) throws SQLException {
        // TODO Auto-generated method stub
        String selectRelationQry= "SELECT friend_id, type FROM fs_relationship WHERE profile_id =?";
        System.out.println("---- In method FetchAndInsertInWall()->fetchFriends - Qry: "+selectRelationQry);
        pst = lCon.prepareStatement(selectRelationQry);
        pst.setInt(1, lActProfId);
        System.out.println("lActProfId: "+ lActProfId );
        ResultSet res3 = pst.executeQuery();
        System.out.println("---- temp--- In method FetchAndInsertInWall()->fetchFriends query has no Results");
        if(!res3.next()){
            System.out.println("---- In method FetchAndInsertInWall()->fetchFriends query has no Results");
        } else {System.out.println("Elements in res3: "+res3.next() +  res3.next() + res3.next());
        }
        pst = null;
        return res3;
    }

I am getting following output on console:

---- In method FetchAndInsertInWall()->fetchFriends - Qry: SELECT friend_id, type FROM fs_relationship WHERE profile_id =?
lActProfId: 5002
---- temp--- In method FetchAndInsertInWall()->fetchFriends query has no Results
Element in res31: false
----> WallInsertions Failed for Uid: 5002
java.sql.SQLException: Illegal operation on empty result set.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:855)
    at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2710)
    at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2851)
    at com.fs.javadbact.FetchDataAndInsertInWall.fetchAndInsertInWall(FetchDataAndInsertInWall.java:64)
    at com.fs.javadbact.ConsumerTest.run(ConsumerTest.java:86)
    at java.lang.Thread.run(Unknown Source)
Jan 12, 2014 3:34:57 AM com.fs.javadbact.ConsumerTest run

Please help me how to resolve this and get proper ResultSet with correct data.

2

There are 2 best solutions below

0
On

I think you've forgotten to declare PreparedStatement before pst variable
write :
PreparedStatement pst = lCon.prepareStatement(selectRelationQry);
rather than :

pst = lCon.prepareStatement(selectRelationQry);
0
On

Use getString() instead of next() to get the values of the row.

If your result has less than three rows you will exhaust the resultset. I do not know if the next() is required to work after returning false once.