我正在尝试根据提供的ID打印出文章。我有一个方法GetArticleById,如果文章的存在或返回NULL,则返回该文章,如果不存在。我也有一个start((方法,该方法提示用户输入ID并在文章中打印出来。我不确定是否正确实现了GetArticleById。另外,我需要一些方向启动((方法来检查是否存在输入的ID。
public Article getArticleById(int id, Connection conn) throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM articles WHERE id = ?")) {
stmt.setInt(1, id);
try (ResultSet r = stmt.executeQuery()) {
if (r.next()) {
return getAllArticles(conn).get(id);
} else {
return null;
}
}
}
}
private void start() throws IOException, SQLException {
try (Connection conn = DBConnectionUtils.getConnectionFromSrcFolder("connection.properties")) {
System.out.print("Enter the article id: > ");
int id = Integer.parseInt(Keyboard.readInput());
}
}
看起来不错,您只需要在start
中调用getArticleById
方法:
private void start() throws IOException, SQLException {
try (Connection conn = DBConnectionUtils.getConnectionFromSrcFolder("connection.properties")) {
System.out.print("Enter the article id: > ");
int id = Integer.parseInt(Keyboard.readInput());
Article article = getArticleById(id, conn);
// DO SOMETHING WITH ARTICLE
}
}
希望这会有所帮助。