Use a ResultSet in java to print a whole table on the screen

0

I know that with resultSet we can do several things with a SELECT done in some table. For example: I know we can get a table and print its contents, listing which columns we want with methods like: 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 want to simply show all the contents of any table I receive per parameter, those methods do not work. It would have to have 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 what columns or columns have in the table.

Exists in ResultSet this?

    
asked by anonymous 30.01.2018 / 00:22

1 answer

2

Does not exist, but ResultSet has methods that allow you 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 named "Person", with the columns named "id", "name" and "remark", the output could look something like this:

[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]
    
30.01.2018 / 12:28