I'm using JDBC for very simple database connectivity.
I have created my connection/statement and executed a query.
I check the query object of the statement in the debugger to confirm that it is sending a proper query.
I then double checked the query (copied straight from debugger) on the database to make sure it returns data.
The returned resultset, however, gives false on .next()
Are there any common pitfalls here that I'm missing?
public List<InterestGroup> getGroups() {
myDB.sendQuery("select distinct group_name From group_members where
username='" + this.username + "'");
ResultSet results = myDB.getResults();
List<InterestGroup> returnList = new ArrayList<InterestGroup>();
try {
while (results.next()) {
returnList.add(new InterestGroup(results.getString("group_name"), myDB));
}
return returnList;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
And the myDB class (simple wrapper that lets me drop the connection/statement code into any project)
public void sendQuery(String query){
this.query = query;
try {
if(statement == null){
statement = connection.createStatement();
}
results = statement.executeQuery(query);
} catch (SQLException e) {
System.out.println(query);
currentError = e;
results = null;
printError(e, "querying");
}
}
public ResultSet getResults(){
return results;
}
EDIT:
Based on suggestions I have mostly revamped my code but still have the same problem. Below is a simplified portion of code that has the same problem.
private boolean attemptLogin(String uName, String pWord) {
ResultSet results;
try{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
connection =DriverManager.getConnection(connectionString,user,password);
PreparedStatement statement = connection.prepareStatement("select username from users where username='testuser'");
results = statement.executeQuery();
if(results != null && results.next()){
System.out.println("found a result");
statement.close();
return true;
}
System.out.println("did not find a result");
statement.close();
return false;
}catch(SQLException e){
e.printStackTrace();
return false;
}
}
I have also hardcoded the query in place for now to eliminate that source of error. Same problem as before (this happens with all queries). Debugger shows all objects getting instantiated and no stack traces are printed. Furthermore, I am able to use the same code (and the more complicated code listed previously) in a different project.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…