【发布时间】: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