How to format resultset printing via System.out.println in Java?

Asked

Viewed 323 times

1

Hello, I am printing on the screen the result of a SELECT that I have stored in a resultset object (sql.Resultset). But it comes out "all crooked". I tried to use the " t" between each printed column, but it didn’t help. Below is the section of the method that interests us:

public void selectCargos(String query){

            try {
                rs = st.executeQuery(query);
                System.out.printf("TABELA DE CARGOS\n\n");
                while (rs.next()){
                    System.out.println("ID: " +rs.getInt("id")+ "\t"+ "Nome do cargo: " +rs.getString("nome")+ "\t" + "Nível do cargo: " +rs.getString("nivel"));
  • PS: This problem only exists if I have only one type of table that I want to print. In a real-life case, where my application will have many "entity" classes, with their respective tables, the ideal is that we use a generic method of printing tables, like the one in this topic here: https://answall.com/questions/2747/usar-a-resultset-em-java-para-imprimir-na-tela-toda-uma-tabela-qualquer/272798#27272798

2 answers

1

You can use a C-type formatting using System.out.format:

String ID = "10"; //rs.getInt("id");
String nomeCargo = "Analista de Sistemas"; //rs.getString("nome");
String nivelCargo = "Senior"; //rs.getString("nivel");
System.out.format("ID: %-4s Nome do cargo: %-50s Nível do cargo: %s", ID , nomeCargo, nivelCargo);

The negative sign is to align to the left and the number is a fixed number of boxes for your string (thus equals a table). See in Ideone.

  • I didn’t know this method "format" either. Good tip. Thanks!

1


 while ( rs.next() ) {
       System.out.println( " ID: " + rs.getInt("id") + "\n Nome do cargo: " + rs.getString("nome")  + "\n Nível do cargo: " + rs.getString("nivel") );
    }

Can print this way:

  System.out.println("##############################################"); 
  System.out.println(" ID: " + rs.getInt("id") );
  System.out.println(" Nome do cargo: " + rs.getString("nome") );
  System.out.println(" Nível do cargo: " + rs.getString("nivel") );
  System.out.println("##############################################");

or

You can override the toString() if you have using an object.

    public String toString() {
      return "ID: " + rs.getInt("id") + "\n Nome do cargo: " + rs.getString("nome") + "\n Nível do cargo: " + rs.getString("nivel");
    }
  • LR10, I get it. Yes, this table is from the Cargo object. All I have to do is implement to string in this class, exactly how did you do it? Or I have to save this data in the table in the form of an object "Cargo"?

  • you are searching from the bank and printing via system.ou. *; you can pass via constructor and then print using toString.

  • I get it. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.