【问题标题】:Print out an Article based on the supplied id根据提供的 id 打印一篇文章
【发布时间】:2019-05-18 22:44:35
【问题描述】:

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

【问题讨论】:

    标签: java sql jdbc prepared-statement persistence


    【解决方案1】:

    看起来不错,您只需要在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
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2013-03-31
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多