【问题标题】:System.out.println() from database into a tableSystem.out.println() 从数据库到表
【发布时间】:2011-07-25 10:57:57
【问题描述】:

目前,我从 MS Access 数据库中提取数据,并在 java 应用程序中 system.out.print 将其打印到控制台。我使用 /t 来分隔数据,但它看起来很尴尬。我想把它放在某种桌子上,以获得更令人愉悦的外观。任何帮助都会非常感谢。

          while(rs.next())
      {
          System.out.print(rs.getInt("season_number")+"\t");
          System.out.print(rs.getInt("season_episode_number")+"\t");
          System.out.print(rs.getInt("series_episode_number")+"\t");
          System.out.print(rs.getString("title")+"\t");
          System.out.print(rs.getString("directed_by")+"\t");
          System.out.print(rs.getString("written_by")+"\t");
          System.out.print(rs.getDate("origional_air_date")+"\t");
          System.out.println(rs.getFloat("viewing_figures")+"\t");

      }
   }

【问题讨论】:

  • 可以考虑String类的format方法。

标签: java user-interface ms-access


【解决方案1】:

我怀疑大量控制台输出的实际应用很少,所以我不会太担心格式化。

但是,如果您对此一无所知...好吧,如果您知道每个字段的最大长度,则可以简单地将每个元素用空格填充到其最大长度。

编辑:这可能对家庭作业有太多帮助,但由于这是一个外围问题,这里有一个例子:

private String pad(String value, int maxLength){
    String retVal = value;
    int remainder = maxLength - value.length();
    for (int i = 0; i < remainder; i++){
        retVal += " ";
    }
    return retVal;
}

对于大型数据集,您可以使用 StringBuilder 对其进行优化,但这就是要点。

【讨论】:

  • 嗨 Riggy,它适用于 uni 课程。尝试脱颖而出真的只是美观。稍后我需要做一些类似的事情来从 servlet 输出到浏览器。谢谢!
  • 好吧,在浏览器中,您将拥有 CSS 和/或 HTML 表格。但是对于控制台,应该很简单,只需编写一个 Pad() 方法,将字段的最大长度和 DB 值作为参数,确定参数的长度,然后用空格填充其余部分。
【解决方案2】:

为了理顺你的输出,最好的解决方案是使用System.out.printf()

由于 printf 与 C' printf 非常相似,您可以使用控制字符来格式化输出。像这样:

System.out.printf( "%-3.2d %-20.20s\n", rs.getInt("season_number"), rs.getString("title") );

检查这个link

【讨论】:

  • 我的回答太糟糕了——这个要好得多。很高兴学习新事物。
  • 一切顺利!您的解决方案也有效。 printf 在 Java 中是相当新的。让我想起了 80 年代的 K&R C……
  • 我喜欢它,但它对编码的数据做出了假设。
  • @glowcoder:如果值得麻烦,可以根据 JDBC 元数据计算出格式字符串。
【解决方案3】:

我创建了一个可能对你有用的 TablePrinter 类

主要方法sn-p:

TablePrinter table = new TablePrinter("MyTest","OtherTest","SillyColumn");
table.addRow("ABC","DEF","GHIJKLMNOPQRSTUVWXYZ");
table.addRow("This is a test","of the","TablePrinter class");

table.print();

结果:

C:\junk>javac TablePrinter.java

C:\junk>java TablePrinter
TablePrinter test driver
| MyTest         | OtherTest | SillyColumn          |
-----------------------------------------------------
| ABC            | DEF       | GHIJKLMNOPQRSTUVWXYZ |
| This is a test | of the    | TablePrinter class   |


C:\junk>

班级:

import java.util.ArrayList;
/**
 * The table printer classes takes a matrix of data and prints it.
 */
class TablePrinter {

    /**
     * The row class represents one row of data.
     * Yes, it's just a wrapper for String[], but it helps
     * keep it simple.
     */
    private static class Row {
        String[] data;
        Row(String[] v) { data = v; }
    }

    /**
     * Contains column header and max width information
     */
    private static class Col {
        String name;
        int maxWidth;
    }

    // matrix information
    Col[] cols;
    ArrayList<Row> rows;

    /**
     * Constructor - pass in columns as an array, or hard coded
     */
    public TablePrinter(String... names) {
        cols = new Col[names.length];
        for(int i = 0; i < cols.length; i++) {
            cols[i] = new Col();
            cols[i].name = names[i];
            cols[i].maxWidth = names[i].length();
        }

        rows = new ArrayList<Row>();
    }

    /**
     * Adds a row - pass in an array or hard coded
     */
    public void addRow(String... values) {
        if(values.length != cols.length) {
            throw new IllegalArgumentException("invalid number of columns in values");
        }

        Row row = new Row(values);
        rows.add(row);
        for(int i = 0; i < values.length; i++) {
            if(values[i].length() > cols[i].maxWidth) {
                cols[i].maxWidth = values[i].length();
            }
        }
    }

    /**
     * Helper method to make sure column headers and 
     * row information are printed the same
     */
    private void print(String v, int w) {
        System.out.print(" ");
        System.out.print(v);
        System.out.print(spaces(w - v.length()));
        System.out.print(" |");
    }

    /**
     * Ugly, poorly documented print method.
     * All pieces of production code should have some
     * methods that you have to decipher. This fulfils that requirement.
     */
    public void print() {

        System.out.print("|");
        for(Col col : cols) {
            print(col.name, col.maxWidth);
        }
        System.out.println("");
        int numDashes = cols.length*3 + 1;
        for(Col col : cols) numDashes += col.maxWidth;
        // TODO make columns have + instead of -
        System.out.println(dashes(numDashes)); 
        for(Row row : rows) {
            System.out.print("|");
            int i = 0;
            for(String v : row.data) {
                print(v,cols[i++].maxWidth);
            }
            System.out.println("");
        }
        System.out.println("");
    }

    // print a specific number of spaces for padding
    private static String spaces(int i) {
        StringBuilder sb = new StringBuilder();
        while(i  --> 0) sb.append(" ");
        return sb.toString();
    }

    // print a specific number of dashes
    private static String dashes(int i) {
        StringBuilder sb = new StringBuilder();
        while(i  --> 0) sb.append("-");
        return sb.toString();
    }

    // test driver
    public static void main(String[] args) {
        System.out.println("TablePrinter test driver");

        TablePrinter table = new TablePrinter("MyTest","OtherTest","SillyColumn");
        table.addRow("ABC","DEF","GHIJKLMNOPQRSTUVWXYZ");
        table.addRow("This is a test","of the","TablePrinter class");

        table.print();
    }

}

【讨论】:

    【解决方案4】:

    我是 Java 新手,作为学习 Java 以及使用 IDE、Javadoc、版本控制、许可、开源等努力的一部分。我编写了一个简单的实用程序类 DBTablePrinter,它打印给定的行表格或java.sql.ResultSet 标准输出,格式化为看起来像带有边框的行和列的表格。我希望它对某人有用。

    这里是 GitHub 上代码仓库的链接:https://github.com/htorun/dbtableprinter

    这里是基本用法:

    // Create a connection to the database
    Connection conn = DriverManager.getConnection(url, username, password);
    
    // Just pass the connection and the table name to printTable()
    DBTablePrinter.printTable(conn, "employees");
    

    它应该打印如下内容:

    Printing 10 rows from table(s) EMPLOYEES
    +--------+------------+------------+-----------+--------+-------------+
    | EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME | GENDER |  HIRE_DATE  |
    +--------+------------+------------+-----------+--------+-------------+
    |  10001 | 1953-09-02 | Georgi     | Facello   | M      |  1986-06-26 |
    +--------+------------+------------+-----------+--------+-------------+
    |  10002 | 1964-06-02 | Bezalel    | Simmel    | F      |  1985-11-21 |
    +--------+------------+------------+-----------+--------+-------------+
        .
        .
    

    感谢所有为这个问题和 stackoverflow.com 做出贡献的人。您的回答对我帮助很大,而且仍然有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多