Last active
April 20, 2018 09:50
-
-
Save Purexo/0b3048edb2f9e45c20b68f9186464dc5 to your computer and use it in GitHub Desktop.
java printResultSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
60 java's lines for print in a nice way a ResultSet in console
Like mysql cli