0

I need to print the output from the database as a table

public static void main(String[] args) {
    
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/walmart?characterEncoding=utf8","root","toor"); 
        
        Statement stmt=con.createStatement();  
        ResultSet rs=stmt.executeQuery("select * from salesperson"); 
        System.out.println(" Employee ID "+" Employee Name "+" Contact "+" Region "+"Sales");  
        while(rs.next())  
            System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getInt(3)+"  "+rs.getString(4)+"  "+rs.getFloat(5));  
          
        //step5 close the connection object  
        con.close();  
    }

    catch(Exception e){ System.out.println(e);}  
      

} }

https://i.stack.imgur.com/uwERi.png

camickr
  • 321,443
  • 19
  • 166
  • 288
sree
  • 17
  • 2

1 Answers1

0

Here is quick untested code:-

ResultSet rs = statement.executeQuery();
   ResultSetMetaData rsmd = rs.getMetaData();
   int columnsCount = rsmd.getColumnCount();
   for (int i = 1; i <= columnsCount; i++) {
              if (i > 1) {
                System.out.print(",  ");
              }
              System.out.print(rsmd.getColumnName(i));
       }
   
   while (rs.next()) {
       for (int i = 1; i <= columnsCount; i++) {
           if (i > 1) {
            System.out.print(",  ");
           }
           String columnValue = rs.getString(i);
           System.out.print(columnValue);
       }
       System.out.println("");
   }
Preeti
  • 222
  • 1
  • 8