mafioso
mafioso

Reputation: 1632

Why doesn't getColumnType work for number type?

I want to get the types of my columns in java.
I do it that way:

    ResultSetMetaData rsmd = rs.getMetaData();
    int type = 0;

    for (int i = 0; i < rsmd.getColumnCount(); i++) {
        type = rsmd.getColumnType(i);

        if (type == Types.VARCHAR) {
            System.out.println("str");
        } else if (type == Types.INTEGER){
            System.out.println("int");
        }

    }

This code works for Strings but it doesn't work for the number type in sql.
Also in the list of types there isn't a number type? How can I fix that problem?

EDIT

Types.NUMERIC is the right answer

Upvotes: 1

Views: 1035

Answers (1)

Serg M Ten
Serg M Ten

Reputation: 5606

ResultSetMetaData column indexes are 1-based, not 0-based, Use a switch statement. The JDBC type returned for a column declared as INTEGER in SQL may vary depending on your RDBMS.

ResultSetMetaData rsmd = rs.getMetaData();
int type = 0;

for (int i = 1; i <= rsmd.getColumnCount(); i++) {
    type = rsmd.getColumnType(i);
    switch (type) {
        case Types.SMALLINT:
            break;
        case Types.INTEGER:
            break;
        case Types.BIGINT:
            break;
        case Types.DECIMAL:
            break;
        case Types.NUMERIC:
            break;
        case Types.FLOAT:
            break;
        case Types.DOUBLE:
            break;
        default:
    }
}

Upvotes: 2

Related Questions