Skip to content

Commit

Permalink
refactor: ResultSet 닫아주기
Browse files Browse the repository at this point in the history
  • Loading branch information
xxeol2 committed Sep 29, 2023
1 parent e8c363c commit 9860d8f
Showing 1 changed file with 8 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ public JdbcTemplate(final DataSource dataSource) {
public void update(String sql, Object... args) {
try (
Connection conn = dataSource.getConnection();
PreparedStatement prepareStatement = conn.prepareStatement(sql)
PreparedStatement prepareStatement = setUpPreparedStatement(conn, sql, args)
) {
setUpPreparedStatement(prepareStatement, args);
prepareStatement.executeUpdate();
} catch (SQLException e) {
log.error(e.getMessage(), e);
Expand All @@ -36,10 +35,9 @@ public void update(String sql, Object... args) {
public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args) {
try (
Connection conn = dataSource.getConnection();
PreparedStatement prepareStatement = conn.prepareStatement(sql)
) {
setUpPreparedStatement(prepareStatement, args);
PreparedStatement prepareStatement = setUpPreparedStatement(conn, sql, args);
ResultSet resultSet = prepareStatement.executeQuery();
) {
if (resultSet.next()) {
return rowMapper.mapRow(resultSet);
}
Expand All @@ -53,10 +51,9 @@ public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) {
try (
Connection conn = dataSource.getConnection();
PreparedStatement prepareStatement = conn.prepareStatement(sql)
) {
setUpPreparedStatement(prepareStatement, args);
PreparedStatement prepareStatement = setUpPreparedStatement(conn, sql, args);
ResultSet resultSet = prepareStatement.executeQuery();
) {
List<T> result = new ArrayList<>();
while (resultSet.next()) {
result.add(rowMapper.mapRow(resultSet));
Expand All @@ -68,9 +65,11 @@ public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) {
}
}

private void setUpPreparedStatement(PreparedStatement prepareStatement, Object... args) throws SQLException {
private PreparedStatement setUpPreparedStatement(Connection conn, String sql, Object... args) throws SQLException {
PreparedStatement prepareStatement = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
prepareStatement.setObject(i + 1, args[i]);
}
return prepareStatement;
}
}

0 comments on commit 9860d8f

Please sign in to comment.