我使用Java中的preparedStatement从MySql中的表中获取两列。查询有效,如果我直接在mySql DB上执行,则返回行。但是对于此方法调用,ResultSet在每个ResultSet.next()调用上都具有值“false”。以下是代码:
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;
}
我在控制台上获得以下输出:
---- 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
请帮我解决这个问题,并使用正确的数据获取正确的ResultSet。
答案 0 :(得分:0)
我认为您忘记在PreparedStatement
变量之前声明pst
写:
PreparedStatement pst = lCon.prepareStatement(selectRelationQry);
而不是:
pst = lCon.prepareStatement(selectRelationQry);
答案 1 :(得分:0)
使用getString()而不是next()来获取行的值。
如果您的结果少于三行,您将耗尽结果集。我不知道在返回false之后是否需要next()。