I have some db I created for school with Tasks. Each Task record have username, description, taskday, taskhour columns.
I want to pull the records by two values: taskhour and taskday or each one individually.
So I have a function that get a task object and check if the taskday or taskhour are empty and prepare the query accordingly. But from some reason something is wrong with the ResultSet...this is my function:
public List<Task> getUserTasks(Task task) throws SQLException {
List<Task> listOfTasks = new ArrayList<>();
try {
String query = "";
PreparedStatement pStatement;
if (task.getDay() != 0 && task.getHour() != 0) {
query = "select * from TASKS where USERNAME=? and TASKDAY=? and TASKHOUR=?";
pStatement = connection.prepareStatement(query);
pStatement.setString(1, task.getUsername());
pStatement.setInt(2, task.getDay());
pStatement.setInt(3, task.getHour());
} else if (task.getDay() == 0) {
query = "select * from TASKS where USERNAME=? and TASKHOUR=?";
pStatement = connection.prepareStatement(query);
pStatement.setString(1, task.getUsername());
pStatement.setInt(2, task.getHour());
} else {
query = "select * from TASKS where USERNAME=? and TASKDAY=?";
pStatement = connection.prepareStatement(query);
pStatement.setString(1, task.getUsername());
pStatement.setInt(2, task.getDay());
}
ResultSet rs;
rs = pStatement.executeQuery();
if (rs.next()) {
Task taskToAdd = new Task();
taskToAdd.setUsername(rs.getString("USERNAME"));
taskToAdd.setDescription(rs.getString("DESCRIPTION"));
taskToAdd.setDay(rs.getInt("TASKDAY"));
taskToAdd.setHour(rs.getInt("TASKHOUR"));
listOfTasks.add(taskToAdd);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return listOfTasks;
}
Am I doing something wrong?
thanks!
Did you want to return more than one row from the resultset?
To get all of the rows use while
not if
:
while (rs.next())
^^^^^
The while
forms a loop, which will be repeated until the expression rs.next()
no longer evaluates to true.
The if
is only performed once. You'll get back at most one row.