Skip to content

Instantly share code, notes, and snippets.

@mikbuch
Forked from jimjam88/print-resultset.java
Last active November 18, 2020 04:07
Show Gist options
  • Save mikbuch/299568988fa7997cb28c7c84309232b1 to your computer and use it in GitHub Desktop.
Save mikbuch/299568988fa7997cb28c7c84309232b1 to your computer and use it in GitHub Desktop.
Print an ResultSet to the console (STDOUT)
// Imports required
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
* Print a result set to system out.
*
* @param rs The ResultSet to print
* @throws SQLException If there is a problem reading the ResultSet
*/
final private static void printResultSet(ResultSet rs) throws SQLException {
// Prepare metadata object and get the number of columns.
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
// Print column names (a header).
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(" | ");
System.out.print(rsmd.getColumnName(i));
}
System.out.println("");
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(" | ");
System.out.print(rs.getString(i));
}
System.out.println("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment