I wasn't sure which parentheses you meant.
At this stage, your DAO should look more like:
Code:
public class RecipeDAO {
private Connection connection;
public RecipeDAO(Connection connection) {
this.connection = connection;
}
public List<Recipe> findAllRecipes() throws SQLException {
Statement s = null;
List<Recipe> recipes = new ArrayList<Recipe>();
try {
s = this.connection.createStatement();
...
// Run your query, iterate over the results and add recipes to the list
...
return recipes;
}
finally {
// Close statement and resultset (but not the connection)
...
}
}
}
You don't want to catch the exception because you aren't doing anything useful with it. For now, let's just declare that you throw it and let your main program deal with it.
In your main program, you'll get your connection from your connection factory and create the DAO:
Code:
private void connectToDatabase() throws SQLException {
ConnectionFactory factory = new ConnectionFactory();
this.connection = connectionFactory.getConnection();
this.recipeDAO = new RecipeDAO(connection);
...
}
When you want a list of recipes, you call the DAO:
Code:
List<Recipe> recipes = recipeDAO.findAllRecipes();
for (Recipe recipe : recipes) {
// Do something with each recipe, e.g. add to the model for a Swing table
}
I'm assuming you understand the basics of using generics (the things in the <> brackets). If not, please say so.
Bookmarks