Recovering an object generically
One option would be to use the method ResultSet.getObject()
. The method documentation says that the type of the returned object will be the standard of JDBC specification for the corresponding database type.
So, just use the operator instanceof
to test the type returned or the method isAssignableFrom()
of the 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 on the results
A second option is to recover the ResultSetMetaData
resulting from the query. It is a more complex form, but allows for accurate information about the columns.
See an example of how to get 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
}
o o.getObject(1), the number 1 would be what? There is a way to catch by passing the column name?
– André Nascimento
@Andrénascimento The number there would be the position of the column in the return of the query. There is the version with the name of the field. Click the first response link and see Javadoc for more details.
– utluiz