gstackoverflow
gstackoverflow

Reputation: 36984

How to know compatible java type for ResultSet column type in runtime?

Following row returns concrete RDBMS type. This type depends on RDBMS.

resultSet.getMetaData().getColumnTypeName(1)

For example in my case it is VARCHAR

Is it possible to know in runtime compatible java type ?

In case of when row above returns VARCHAR compatible type is String.

I want to solve which methods invoke:

resultSet.getXXX(...)

Upvotes: 0

Views: 1892

Answers (2)

Mark Rotteveel
Mark Rotteveel

Reputation: 109014

You can use the method ResultSetMetaData.getColumnClassName(int):

Returns the fully-qualified name of the Java class whose instances are manufactured if the method ResultSet.getObject is called to retrieve a value from the column. ResultSet.getObject may return a subclass of the class returned by this method.

You can also code it out as demonstrated by the answer of Daniel Scott, although then I would opt to use ResultSetMetaData.getColumnType(int) instead, that way you can switch using the constants of java.sql.Types or (Java 8) java.sql.JDBCType.

You can look at Appendix B of the JDBC 4.2 standard to see which SQL types map to which Java types.

Upvotes: 3

Daniel Scott
Daniel Scott

Reputation: 7913

I don't think so.

When I did this, I had to implement what was basically a big switch/case statement which obtained the column type name and then executed the relevant resultSet.getXXX() method.

pseudocode:

if(type.equals('VARCHAR') {
  String value = resultSet.getString(column)
} else if (type.equals('TIMESTAMP') {
  Date value = resultSet.getDate(column)
} else if (type.equals('INTEGER') {
  Integer value = resultSet.getInteger(column)
} else
  throw new CannotParseTypeFromColumnException("Don't know how to handle type " + type);
}

If you do find a better solution, I'd love to know.

Upvotes: 0

Related Questions