tokuhirom's 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);
        }
    }
Created: 2020-06-26 18:49:46 +0900
Updated: 2020-06-26 18:49:46 +0900