如何从数据库中正确打印出所获取的数据。
在控制台上打印出来就像这样 - > see here
//initialize the connection
try{
Connection conn1=DriverManager.getConnection("jdbc:mysql://localhost/test","root","****");
String query1= "SELECT * FROM student_table";
Statement stmt1= conn1.createStatement();
ResultSet res1=stmt1.executeQuery(query1);
// Print the result
System.out.println("id \t\t "+"name\t\t "+"class\t\t\t "+"age\n");
while(res1.next()){
System.out.println(res1.getString("id")+"\t\t "
+res1.getString("name")+"\t\t "
+res1.getString("class")+"\t\t "
+res1.getString("age"));
}
}catch(Exception e){
System.err.println(e);
}
}
答案 0 :(得分:1)
您可以使用String.format
while(res1.next()){
System.out.println(String.format("%-16s",res1.getString("id"))
+String.format("%-16s",res1.getString("name"))
+String.format("%-24s",res1.getString("class"))
+String.format("%-16s",res1.getString("age")));
}
由于\ t包含8个空格,我提供了'% - 16s'基于您在结果集的标题中给出的\ t值。希望它有助于解决您的问题。 输出图像在此处给出:https://i.stack.imgur.com/Qn6py.jpg