Ways to get bank values with Resultset

Asked

Viewed 8,135 times

3

Ways to get values from the Java database (JDBC).

 public static Connection getConnection(){
        /* 1. Faz a conexao com a base de dados */
        /* 2. Retorna qual banco ira trabalhar */

        Connection connection=null;

        try {
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/base", "postgres", "postgres");
            System.out.print("Conexao com o banco de dados efetuada com sucesso!");

        } catch (SQLException ex) {
            Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
            System.out.print("Erro durante a conexao com o banco de dados!");
        }

        return connection;
    }   

Map<String,String> fields_values = new HashMap<String,String>(); // Chave: Valor

String sql = "SELECT id, nome, idade, endereco FROM PESSOA";

Connection conexao = getConnection(); // Chama método para retornar conexão com o banco
prepared = conexao.prepareStatement(sql); // Prepara o SQL para ser executado no banco

ResultSet result = prepared.executeQuery(sql); // Retorno do banco de dados

I believe there must be another way to take the values from the database without having to use methods such as result.getInt(), result.()getString, result.getFloat().

  1. I could get the values from the database another way?
  2. I can obtain the values in a more simplified way to store in the variable fields_values?

1 answer

3


Yes, you can recover ResultSetMetaData of ResultSet and using getColumnCount() you would recover the amount of columns to then recover the values of ResultSet by the position of the column.

To recover the ResultSetMetaData and the amount of columns you should do this way:

How are you using a map of strings to store the values a form of values would be this:

final ResultSetMetaData metaRS = rs.getMetaData();
final int columnCount = metaRS.getColumnCount();

Then we will have to retrieve all column values as a Object and call toString of it, because we may not know exactly the type of data in the database. As we do not have the name also, we will take by Indian, something like this:

while (rs.next()) {
    for (int i = 1; i <= columnCount; i++) {
        final Object value = rs.getObject(i);
        fieldsValues.put(metaRS.getColumnName(i), value.toString());
    }
}

If you want to print the values on your map to check if they are OK you can do something this way:

final Set<Map.Entry<String, String>> entries = fieldsValues.entrySet();
for (final Map.Entry<String, String> entry : entries) {
    System.out.println(String.format("Key: %s | Value: %s", entry.getKey(), entry.getValue()));
}

That will generate something like this:

Key: id | Value: 1
Key: idade | Value: 25
Key: nome | Value: Nome 1
Key: endereco | Value: Endereco 1

Note also that in this case it is only possible to store for one line, since it will always overwrite the values of your map.

A complete example would be this:

final Map<String, String> fieldsValues = new HashMap<>();

final Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/base", "postgres", "postgres");
final String sql = "SELECT id, nome, idade, endereco FROM PESSOA";
final PreparedStatement ps = conn.prepareStatement(sql);
final ResultSet rs = ps.executeQuery();

final ResultSetMetaData metaRS = rs.getMetaData();
final int columnCount = metaRS.getColumnCount();

while (rs.next()) {
    for (int i = 1; i <= columnCount; i++) {
        final Object value = rs.getObject(i);
        fieldsValues.put(metaRS.getColumnName(i), value.toString());
    }
}

Browser other questions tagged

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