jdbc: Get the SQL Type Name from java.sql.Type code

AndreasT picture AndreasT · Jun 22, 2011 · Viewed 41.6k times · Source

I have an array with Field Names and jdbc Type codes. (Those int codes that you can find in

http://download.oracle.com/javase/1.4.2/docs/api/constant-values.html#java.sql.Types.BIT

I use a level 4 Driver.

I can't figure out how to ask the driver for the corresponding SQL (DDL) Type names. It would be useful in jdbc and in native dialects.

I have
(CustomerId, 1) (CustomerName, -8)

and I want

(customerId, INT) (customerId, VARCHAR(200))

Where can I find functions that help me with that? I am using jdbc in jython via zxJDBC, so I can use all java and python DB API 2.0 functionality.

Answer

k427h1c picture k427h1c · Mar 6, 2013

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