Skip to content

Instantly share code, notes, and snippets.

@Purexo
Last active April 20, 2018 09:50
Show Gist options
  • Save Purexo/0b3048edb2f9e45c20b68f9186464dc5 to your computer and use it in GitHub Desktop.
Save Purexo/0b3048edb2f9e45c20b68f9186464dc5 to your computer and use it in GitHub Desktop.
java printResultSet
private void printRS(ResultSet rs) throws SQLException {
List<String> header = new ArrayList<>();
Map<Integer, Integer> max = new HashMap<>();
// generate header map
ResultSetMetaData meta = rs.getMetaData();
for (int i = 1; i <= meta.getColumnCount(); i++) {
String collumn = meta.getColumnName(i);
// compute max column width
if (collumn.length() > max.getOrDefault(i, 0)) {
max.put(i, collumn.length());
}
header.add(collumn);
}
// generate table result
List<List<String>> table;
for (table = new ArrayList<>(); rs.next();) {
List<String> line = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++) {
String cell = rs.getString(i);
// compute max column width
if (cell.length() > max.getOrDefault(i, 0)) {
max.put(i, cell.length());
}
line.add(cell);
}
table.add(line);
}
// get list of max cell width ordoned by key
List<Integer> maxList = max.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
// generate format line string
String format = maxList.stream()
.map(cellMax -> String.format("%%-%ds", cellMax))
.collect(Collectors.joining(" | ", "| ", " |%n"));
// generate line separator
String lineSeparator = maxList.stream()
.map(cellMax -> new String(new char[cellMax]).replace("\0", "-"))
.collect(Collectors.joining("-+-", "+-", "-+"));
// print ResultSet in a nice cli mysql appearance
System.out.println(lineSeparator);
System.out.format(format, header.toArray());
System.out.println(lineSeparator);
for (List<String> line : table) {
System.out.format(format, line.toArray());
}
System.out.println(lineSeparator);
}
@Purexo
Copy link
Author

Purexo commented Apr 20, 2018

60 java's lines for print in a nice way a ResultSet in console

Like mysql cli

+----------+----------+
| column_1 | column_2 |
+----------+----------+
| value_1  | value_2  |
+----------+----------+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment