Use a java Resultset to print an entire table on the screen

Asked

Viewed 940 times

0

I know that with the resultset we can do several things with a SELECT done in some table. For example: I know that we can take a table and print its contents, listing which columns we want with methods such as: getString and getInt.

Conection con = ........
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM Clientes");

while(rs.next()) {

  String nome = rs.getString("Nome");
  System.out.println("Nome do Cliente: " + nome);
}

But if I just want to show you all the content of any table I receive by parameter, they don’t serve those methods. There would have to be something like:

System.out.println (rs.getAll());

That is, I want a method that takes the result of my SELECT * and shows on the screen, regardless of which or how many columns are in the table.

Exsite on Resultset this?

1 answer

2


It doesn’t exist, but the ResultSet has methods to create such functionality. Example:

public class ResultSetExibirTabela {

    public static void main(String[] args) throws SQLException {
        //Coloque as informações de conexão do seu banco
        Connection conexao = DriverManager.getConnection("url","meuUsuario", "minhaSenha");

        //Entre com o nome da sua tabela
        exibirTabela(conexao, "nomeDaTabela");

        conexao.close();
    }

    public static void exibirTabela(Connection conexao, String nomeDaTabela) throws SQLException {
        ResultSet rs = conexao.prepareStatement("SELECT * FROM " + nomeDaTabela).executeQuery();

        ResultSetMetaData metaData = rs.getMetaData();
        int numeroDeColunas = metaData.getColumnCount();

        while (rs.next()) {
            StringJoiner joiner = new StringJoiner(", ", "[", "]");
            for (int coluna = 1; coluna <= numeroDeColunas; coluna++) {
                String nomeDaColuna = metaData.getColumnName(coluna);
                joiner.add(nomeDaColuna + "=" + rs.getObject(coluna));
            }
            System.out.println(joiner.toString());
        }

        rs.close();
    }
}

In a table called "Person", with the columns of name "id", "name" and "observation", the output could be something similar to that:

[id=1, nome=Pessoa 1, observacao=Esta é a Pessoa 1]
[id=2, nome=Pessoa 2, observacao=Esta é a Pessoa 2]
[id=3, nome=Pessoa 3, observacao=Esta é a Pessoa 3]
  • :The Excellent. I didn’t know some guys you used there. It helped a lot. Thank you!

  • One more thing: Is this "prepareStatement()" method not used only when, in our system, we often have the characteristic of executing the same "statement? In other cases we could directly use a Statement st; st.executeQuery(); ?? What is best practice?

  • Felipe Marinho: a problem with using Stringjoiner, is that it simply puts one string on the side of the other. What generates your table misaligned, depending on how many characters each table item has: [ID = 1,NAME = Programmer,NIVEL = technician] [ID = 2,NAME = Systems Analyst,NIVEL = technical] [ID = 5,NAME = Tester,NIVEL = technical] [ID = 6,NAME = Tester,NIVEL = technical]

  • 1

    @Lucaspletsch On the PreparedStatement: besides this benefit you cited, it also help prevent SQL Injection if used correctly. In this example I gave, the use of it is not necessary, you can use a simple Statement. As to the StringJoiner: he just joins the Strings with the delimiters, prefix and suffix informed. If you want a more elaborate formatting (which displays the data as a table), you need to check which is the longest value of each column to set its minimum size.

  • About Stringjoiner: exact. I just haven’t figured out how to edit the "column" width yet. kkk

  • 1

    @Lucaspletsch Suppose the String calling for maior be the largest String of the column, and that s be any other String of that column. To edit the "width" just do int v = (maior.length() - s.length()) / 2. Now just add v blank spaces before and after s (case maior.length() - s.length() be odd, you will have to add one more space before or after s).

Show 1 more comment

Browser other questions tagged

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