我有以下代码,它应该在java中显示格式resultSet
。然而,它没有做到它想象的那样。我想知道为什么我得到这种格式奇怪的输出。
id name age address salary
1 Paul 32California 23000.0
2 Steeve 24New Jersy 22000.0
4 Andrew 24Washinghton 25000.0
3 Georg 29Colorado 21000.0
5 Andy 26Texas2 28000.0
public void displayResultSet(ResultSet resultSet2) throws SQLException{
ResultSetMetaData resultSetMetaData2 = resultSet2.getMetaData();
int count2 = resultSetMetaData2.getColumnCount();
Object[] objects = new Object[count2];
for (int a = 1; a<=count2;a++){
System.out.printf("%1$12s", resultSetMetaData2.getColumnName(a));
}
System.out.println("");
while (resultSet2.next()) {
for (int a = 1; a<=count2;a++){
Object o2 = resultSet2.getObject(a);
objects[a-1] = o2.toString();
System.out.printf("%1$12s", o2.toString());
}
System.out.println("");
}
}
插入问题看起来像这样:
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul',32,'California',23000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Steeve',24,'New Jersy',22000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Georg',29,'Colorado',21000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Andrew',26,'Washinghton',25000.00);
INSERT INTO COMPANY2 (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Andy',26,'Texas2',28000.00);
非常感谢任何帮助。
答案 0 :(得分:1)
在Java Formatter
中,width指定要写入输出的最小字符数。如果希望截断长文本字段(如Address),则应尝试使用精度。此外,您依靠Object的toString()
方法来格式化非文本字段,因此您可能希望先修改它们:
System.out.printf("%12.12s", o2.toString().trim());