I got everything working and it prints the right result with header (column name) and value. Howev开发者_JAVA技巧er I wanted to change a plain and unorganized result into a really nice output table format just like MySql table result with dash lines from query. How do I do that?
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM quarter");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for(int i = 1; i <= numberOfColumns; i++)
{
System.out.print(rsMetaData.getColumnLabel(i) + " ");
}
System.out.println();
while (rs.next())
{
for(int e = 1; e <= rsMetaData.getColumnCount(); e++)
{
System.out.print(rs.getString(e) + " ");
}
System.out.println();
}
You can use String.format()
method with appropriate format string.
For instance,
StringBuilder sb=new StringBuilder();
for(int i = 1; i <= numberOfColumns; i++)
{
sb.append(String.format("| %-10s",rsMetaData.getColumnLabel(i)));
}
You can have function for that. Change the parameter as need while calling.
public static void printHeader(ResultSet rs, char symbol, int width) throws Exception
{
ResultSetMetaData rsmd = rs.getMetaData();
int nCols = rsmd.getColumnCount();
for(int i = 1; i <= nCols; ++i)
System.out.printf("%-10s ", rsmd.getColumnLabel(i));
System.out.printf("\n");
for(int i = 0; i < width; ++i)
System.out.printf("%c", symbol);
}
//call <br>
printHeader(rs,'-',70);
精彩评论