1

I got everything working and it prints the right result with header (column name) and value. However 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();
}

2 Answers 2

3

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)));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.