我正在尝试根据提供的 ID 打印一篇文章。我有一个方法 getArticleById ,如果文章存在则返回该文章,如果不存在则返回 null 。我还有一个 start() 方法,它提示用户输入 ID 并打印文章(如果存在)。我不确定我是否正确实现了 getArticleById 。另外,我需要一些指导 start() 方法来检查输入的 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
}
}
希望这有帮助。
关于java - 根据提供的 id 打印文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203409/