Skip to content

Instantly share code, notes, and snippets.

@jimjam88
Last active February 16, 2019 15:37
Show Gist options
  • Save jimjam88/8559599 to your computer and use it in GitHub Desktop.
Save jimjam88/8559599 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 public static void printResultSet(ResultSet rs) throws SQLException
{
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
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("");
}
}
@mikbuch
Copy link

mikbuch commented Jul 6, 2018

Hi, I added printing column names (header):
// Print column names (a header).
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(" | ");
System.out.print(rsmd.getColumnName(i));
}

Check my forked version here: https://gist.github.com/mikbuch/299568988fa7997cb28c7c84309232b1

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