Use Resultset without knowing the column type

Asked

Viewed 1,462 times

13

I need to use a Resultset that returned the data of a query in the database. I’m making a very generic class, it can be used in any table, so I don’t know what kind of data it’s returning.

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

How to do this without knowing the type of die in the column?

1 answer

11


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 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.

Browser other questions tagged

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