Blog

適当に JDBC でデータとってきてダンプするスニペット

生JDBCで適当にデータ出してデバッグしたいって時につかうやつです。

    protected void selectAndPrint(Connection connection, String query) {
        log.info("======> dumpTable: {} <====", query);
        try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                ResultSetMetaData metaData = rs.getMetaData();
                log.info("| {} |", IntStream.range(0, metaData.getColumnCount())
                                            .mapToObj(i -> {
                                                try {
                                                    return metaData.getColumnName(i + 1);
                                                } catch (SQLException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }).collect(Collectors.joining(" | ")));
                while (rs.next()) {
                    log.info("| {} |", IntStream.range(0, metaData.getColumnCount())
                                                .mapToObj(i -> {
                                                    try {
                                                        return rs.getString(i + 1);
                                                    } catch (SQLException e) {
                                                        throw new RuntimeException(e);
                                                    }
                                                }).collect(Collectors.joining(" | ")));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }