2011-09-27 170 views
1

我得到了一切正常,並打印正確的結果報頭(列名)和值。不過,我想將普通和無組織的結果更改爲非常好的輸出表格式,就像查詢中帶有虛線的MySql表結果一樣。我怎麼做?Java SQL輸出格式表結果

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

您可以使用String.format()方法和適當的format string

例如,

StringBuilder sb=new StringBuilder(); 

for(int i = 1; i <= numberOfColumns; i++) 
{ 
    sb.append(String.format("| %-10s",rsMetaData.getColumnLabel(i))); 
} 
0

可以擁有該功能。在調用時根據需要更改參數。

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