基于ID查询文章的代码实现正确性验证及方法完善咨询
问题分析与解决方案
一、修复getArticleById方法的核心问题
你的getArticleById逻辑存在明显漏洞:明明已经通过SQL精准查询到了指定ID的文章结果集,却没有直接从ResultSet中提取数据构建Article对象,反而调用getAllArticles(conn).get(id)——这不仅多做了一次全表查询浪费性能,还可能因为getAllArticles返回的集合结构(比如不是以数据库ID为Key的Map)导致错误结果。
正确的实现应该直接从查询结果中读取字段,实例化Article返回:
public Article getArticleById(int id, Connection conn) throws SQLException { // 建议明确列出查询字段,避免表结构变更引发的潜在问题 try (PreparedStatement stmt = conn.prepareStatement( "SELECT id, title, content, author, publish_date FROM articles WHERE id = ?")) { stmt.setInt(1, id); try (ResultSet r = stmt.executeQuery()) { if (r.next()) { // 假设Article类有对应的Setter方法或全参构造器 Article article = new Article(); article.setId(r.getInt("id")); article.setTitle(r.getString("title")); article.setContent(r.getString("content")); article.setAuthor(r.getString("author")); article.setPublishDate(r.getTimestamp("publish_date")); return article; } else { return null; // 未找到对应ID的文章,返回null } } } }
二、完善start方法,加入校验与用户友好逻辑
你的start方法目前只完成了输入ID的第一步,缺少查询、存在性校验和异常处理。下面是完善后的版本,兼顾了功能完整性和用户体验:
private void start() throws IOException, SQLException { try (Connection conn = DBConnectionUtils.getConnectionFromSrcFolder("connection.properties")) { while (true) { System.out.print("Enter the article id (type 'exit' to quit): > "); String input = Keyboard.readInput().trim(); // 处理用户退出请求 if ("exit".equalsIgnoreCase(input)) { System.out.println("Exiting program..."); break; } // 校验输入是否为有效整数 int id; try { id = Integer.parseInt(input); } catch (NumberFormatException e) { System.out.println("Invalid input! Please enter a valid integer ID or 'exit'."); continue; } // 查询并校验文章是否存在 Article article = getArticleById(id, conn); if (article != null) { System.out.println("\n=== Article Details ==="); System.out.println("ID: " + article.getId()); System.out.println("Title: " + article.getTitle()); System.out.println("Author: " + article.getAuthor()); System.out.println("Content:\n" + article.getContent()); System.out.println("Publish Date: " + article.getPublishDate()); } else { System.out.println("Oops! No article found with ID: " + id); } System.out.println("-------------------------\n"); } } }
关键改进点:
- 加入非整数输入的异常捕获,避免程序崩溃
- 增加退出逻辑,让用户可以主动结束操作
- 通过判断
getArticleById的返回值是否为null,完成文章存在性校验 - 存在则打印完整文章信息,不存在则给出明确提示
- 用循环实现多次查询,提升交互体验
内容的提问来源于stack exchange,提问作者saum
相关产品推荐
相关产品推荐

