Java SQL输出格式表结果

时间:2023-01-14 10:50:44

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?

我得到了一切工作,它打印出正确的结果与标题(列名称)和值。但是我想将一个简单和无组织的结果更改为一个非常好的输出表格式,就像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 个解决方案

#1


3  

You can use String.format() method with appropriate format string.

您可以将String.format()方法与适当的格式字符串一起使用。

For instance,

例如,

StringBuilder sb=new StringBuilder();

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

#2


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

#1


3  

You can use String.format() method with appropriate format string.

您可以将String.format()方法与适当的格式字符串一起使用。

For instance,

例如,

StringBuilder sb=new StringBuilder();

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

#2


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