Java SQL输出格式表结果

时间:2011-09-27 01:03:52

标签: java mysql database-connection

我把所有东西都搞定了,它用标题(列名)和值打印出正确的结果。但是我想将一个简单和无组织的结果更改为一个非常好的输出表格式,就像MySql表格结果一样,带有来自查询的虚线。我该怎么做?

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 个答案:

答案 0 :(得分:3)

您可以使用String.format()方法和相应的format string

例如,

StringBuilder sb=new StringBuilder();

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

答案 1 :(得分: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);