根据提供的ID打印出文章

时间:2019-05-18 22:44:35

标签: java sql jdbc prepared-statement

我正在尝试根据提供的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());
    }
}

1 个答案:

答案 0 :(得分:0)

看起来不错,您只需要在getArticleById中调用start方法:

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
    }
}

希望这会有所帮助。