-2

How to properly print out the acquired data from the database.

Printing out on the console looks like this -> 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);
    }
}
Klayd Pro
  • 1
  • 1
  • 2
  • 7
  • 1
    Possible duplicate of [Output in a table format in Java's System.out](https://stackoverflow.com/questions/2745206/output-in-a-table-format-in-javas-system-out) – d.j.brown Apr 05 '18 at 08:27

1 Answers1

1

You could format like this using 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")));
            }  

Since \t contains 8 spaces, I have provided the '%-16s' based on the \t value which you have gave in the header of the resultset. Hope it helps to solve your issue. The image of the output is given here: https://i.stack.imgur.com/Qn6py.jpg

Vignesh
  • 686
  • 6
  • 10