jdbc: Get the SQL Type Name from java.sql.Type code
Java 8 and later: JDBCType
& SQLType
With improvements in the API's, as of Java 8 and JDBC 4.2, we have JDBCType
and SQLType
, and in the same spirit as some of the other examples can be simply used as follows:
String typeName = JDBCType.valueOf(-5).getName();
But of course, why using the numeric types to begin with. Make a habit, and switch over from numeric's to the enum
constants defined in JDBCType
:
String typeName = JDBCType.BIGINT.getName();
et voilà!
However, that might not be enough to have something good enough for using in a DDL ... you might need to implement vendor specific translation. As an example, you might need to consider to translate VARCHAR
to VARCHAR2
in the case of Oracle.
To specifically answer "Get the SQL Type Name from java.sql.Type code", if you are using a version of java that can do reflection, here is a small utility method that pretty much does the same thing:
public Map<Integer, String> getAllJdbcTypeNames() {
Map<Integer, String> result = new HashMap<Integer, String>();
for (Field field : Types.class.getFields()) {
result.put((Integer)field.get(null), field.getName());
}
return result;
}
Add import java.lang.reflect.Field;
to your import declarations. Once you have that in place, simply use it as follows:
...
Map<Integer, String> jdbcMappings = getAllJdbcTypeNames();
String typeName = jdbcMappings.get(-5); // now that will return BIGINT
...