Use ResultSet without knowing the column type

12

I need to use a ResultSet that returned the data from a query in the Database. I am making a very generic class, it will be able to be used on any table, so I do not know what kind of data it is returning.

For example, the Name column will return a String. Knowing this I would do: resultSet.getString (1).

How to do this without knowing the data type of the column?

    
asked by anonymous 17.01.2014 / 17:54

1 answer

10

Retrieving an object generically

One option would be to use the ResultSet.getObject() . The method documentation says that the type of object returned will be the JDBC specification to the corresponding type of database.

So, just use the instanceof operator to test the returned type or the isAssignableFrom() " class. For example:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
Object o = rs.getObject(1);

if (Integer.class.isAssignableFrom(o.getClass())) 
    System.out.println("true"); //verdadeiro

if (o instanceof Integer)
    System.out.println("true"); //verdadeiro

Getting detailed information about the results

A second option is to retrieve the resulting ResultSetMetaData the query. This is a more complex form, but it allows you to get accurate information about the columns.

See an example of how to get the columns and types:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();

//quantidade de colunas
int numberOfColumns = rsmd.getColumnCount();

int type = rsmd.getColumnType(1);
if (type == Types.VARCHAR || type == Types.CHAR) {
    //executa alguma ação
}
    
17.01.2014 / 18:14