根据提供的 id 打印出一篇文章

Print out an Article based on the supplied id

我正在尝试根据提供的 ID 打印一篇文章。我有一个 getArticleById 方法,如果它存在 returns 文章,如果不存在则 returns 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
    }
}

希望对您有所帮助。