此代码有效,它从数据库中获取数据。看看输出,你会看到问题?如何格式化此数据,以便cols显示内联。我不想使用复杂的表或数据集来输出我的结果。我只想在每个cols之间添加“\ t”。
这是输出:
ID FIRSTNAME LASTNAME USERNAME AGE
2 Dave Bill DaveB 30
3 Jane Mark JaneM 37
4 Voo Gorge VooG 50
public class ex02 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess:Database11.accdb";
Connection con;
Statement stmt;
String query = "Select * from user";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();
for (int i = 1; i <= columns; i++) {
System.out.print(rsmd.getColumnLabel(i) + "\t");
}
System.out.println();
// Display columns data from database
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.println();
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
答案 0 :(得分:0)
您可以从Apache Commons中查看StringUtils.rightPad()(或者自己编写相应的代码)。使用rightPad并将列值限制为最大长度应该可以为您提供格式良好的输出。
答案 1 :(得分:0)
您可以按固定长度向左或向右对齐列。以下是将它们全部设置为相同理由的示例。
public static void main(String[] args) throws Exception {
List<String[]> dataTable = new ArrayList() {{
add(new String[] {"ID", "FIRSTNAME", "LASTNAME", "USERNAME", "AGE"});
add(new String[] {"2", "Dave", "Bill", "DaveB", "30"});
add(new String[] {"3", "Jane", "Mark", "JaneM", "37"});
add(new String[] {"4", "Voo", "Gorge", "VooG", "50"});
}};
// Left justified 15 character width
System.out.println("Left Justified");
for (String[] row : dataTable) {
for (String col : row) {
System.out.printf("%-15s", col);
}
System.out.println();
}
System.out.println();
// Right justified 15 character width
System.out.println("Right Justified");
for (String[] row : dataTable) {
for (String col : row) {
System.out.printf("%15s", col);
}
System.out.println();
}
}
结果:
Left Justified
ID FIRSTNAME LASTNAME USERNAME AGE
2 Dave Bill DaveB 30
3 Jane Mark JaneM 37
4 Voo Gorge VooG 50
Right Justified
ID FIRSTNAME LASTNAME USERNAME AGE
2 Dave Bill DaveB 30
3 Jane Mark JaneM 37
4 Voo Gorge VooG 50