Example usage for java.sql DatabaseMetaData getTypeInfo

List of usage examples for java.sql DatabaseMetaData getTypeInfo

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getTypeInfo.

Prototype

ResultSet getTypeInfo() throws SQLException;

Source Link

Document

Retrieves a description of all the data types supported by this database.

Usage

From source file:Main.java

public static void main(String[] argv) {
    Connection connection = null;
    Statement statement;/*from  w  w  w .j a va 2  s .co  m*/
    ResultSet rs;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        DatabaseMetaData md = connection.getMetaData();
        statement = connection.createStatement();

        System.out.println("getURL() - " + md.getURL());
        System.out.println("getUserName() - " + md.getUserName());
        System.out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion());
        System.out.println("getDriverMajorVersion - " + md.getDriverMajorVersion());
        System.out.println("getDriverMinorVersion - " + md.getDriverMinorVersion());
        System.out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh());

        System.out.println("<H1>Feature Support</H1>");
        System.out.println(
                "supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>");
        System.out.println("supportsBatchUpdates - " + md.supportsBatchUpdates());
        System.out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames());
        System.out.println("supportsPositionedDelete - " + md.supportsPositionedDelete());
        System.out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins());
        System.out.println("supportsStoredProcedures - " + md.supportsStoredProcedures());
        System.out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers());
        System.out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());
        System.out.println("getMaxRowSize - " + md.getMaxRowSize());
        System.out.println("getMaxStatementLength - " + md.getMaxStatementLength());
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxConnections - " + md.getMaxConnections());
        System.out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength());

        System.out.println("getTableTypes()");
        rs = md.getTableTypes();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
        System.out.println("getTables()");
        rs = md.getTables("accounts", "", "%", new String[0]);
        while (rs.next()) {
            System.out.println(rs.getString("TABLE_NAME"));
        }
        System.out.println("Transaction Support");
        System.out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation());
        System.out
                .println("dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions());

        System.out.println("General Source Information");
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable());
        System.out.println("getTimeDateFunctions - " + md.getTimeDateFunctions());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());

        System.out.println("getTypeInfo()");
        rs = md.getTypeInfo();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:CreateNewType.java

private static Vector getDataTypes(Connection con, String typeToCreate) throws SQLException {
    String structName = null, distinctName = null, javaName = null;

    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)

    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));

    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
        int codeNumber = rs.getInt("DATA_TYPE");
        String dbmsName = rs.getString("TYPE_NAME");
        String createParams = rs.getString("CREATE_PARAMS");

        if (codeNumber == Types.STRUCT && structName == null)
            structName = dbmsName;/*w ww .ja v a2s.  co  m*/
        else if (codeNumber == Types.DISTINCT && distinctName == null)
            distinctName = dbmsName;
        else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
            javaName = dbmsName;
        else {
            for (int i = 0; i < dataTypes.size(); i++) {
                // find entry that matches the SQL code, 
                // and if local type and params are not already set,
                // set them
                DataType type = (DataType) dataTypes.get(i);
                if (type.getCode() == codeNumber) {
                    type.setLocalTypeAndParams(dbmsName, createParams);
                }
            }
        }
    }

    if (typeToCreate.equals("s")) {
        int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
        rs = dbmd.getUDTs(null, "%", "%", types);
        while (rs.next()) {
            String typeName = null;
            DataType dataType = null;

            if (dbmd.isCatalogAtStart())
                typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
                        + rs.getString(3);
            else
                typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
                        + rs.getString(1);

            switch (rs.getInt(5)) {
            case Types.STRUCT:
                dataType = new DataType(Types.STRUCT, typeName);
                dataType.setLocalTypeAndParams(structName, null);
                break;
            case Types.DISTINCT:
                dataType = new DataType(Types.DISTINCT, typeName);
                dataType.setLocalTypeAndParams(distinctName, null);
                break;
            case Types.JAVA_OBJECT:
                dataType = new DataType(Types.JAVA_OBJECT, typeName);
                dataType.setLocalTypeAndParams(javaName, null);
                break;
            }
            dataTypes.add(dataType);
        }
    }

    return dataTypes;
}

From source file:CreateNewTable.java

private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;

    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)

    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));

    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
        int codeNumber = rs.getInt("DATA_TYPE");
        String dbmsName = rs.getString("TYPE_NAME");
        String createParams = rs.getString("CREATE_PARAMS");

        if (codeNumber == Types.STRUCT && structName == null)
            structName = dbmsName;/*  w w  w  .ja  va2  s . c om*/
        else if (codeNumber == Types.DISTINCT && distinctName == null)
            distinctName = dbmsName;
        else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
            javaName = dbmsName;
        else {
            for (int i = 0; i < dataTypes.size(); i++) {
                // find entry that matches the SQL code, 
                // and if local type and params are not already set,
                // set them
                DataType type = (DataType) dataTypes.get(i);
                if (type.getCode() == codeNumber) {
                    type.setLocalTypeAndParams(dbmsName, createParams);
                }
            }
        }
    }

    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
        String typeName = null;
        DataType dataType = null;

        if (dbmd.isCatalogAtStart())
            typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "." + rs.getString(3);
        else
            typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator() + rs.getString(1);

        switch (rs.getInt(5)) {
        case Types.STRUCT:
            dataType = new DataType(Types.STRUCT, typeName);
            dataType.setLocalTypeAndParams(structName, null);
            break;
        case Types.DISTINCT:
            dataType = new DataType(Types.DISTINCT, typeName);
            dataType.setLocalTypeAndParams(distinctName, null);
            break;
        case Types.JAVA_OBJECT:
            dataType = new DataType(Types.JAVA_OBJECT, typeName);
            dataType.setLocalTypeAndParams(javaName, null);
            break;
        }
        dataTypes.add(dataType);
    }

    return dataTypes;
}

From source file:Main.java

private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;

    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)

    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));

    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
        int codeNumber = rs.getInt("DATA_TYPE");
        String dbmsName = rs.getString("TYPE_NAME");
        String createParams = rs.getString("CREATE_PARAMS");

        if (codeNumber == Types.STRUCT && structName == null)
            structName = dbmsName;/*from   w  w  w  .  j  av a2  s. c  om*/
        else if (codeNumber == Types.DISTINCT && distinctName == null)
            distinctName = dbmsName;
        else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
            javaName = dbmsName;
        else {
            for (int i = 0; i < dataTypes.size(); i++) {
                // find entry that matches the SQL code,
                // and if local type and params are not already set,
                // set them
                DataType type = (DataType) dataTypes.get(i);
                if (type.getCode() == codeNumber) {
                    type.setLocalTypeAndParams(dbmsName, createParams);
                }
            }
        }
    }

    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
        String typeName = null;
        DataType dataType = null;

        if (dbmd.isCatalogAtStart())
            typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "." + rs.getString(3);
        else
            typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator() + rs.getString(1);

        switch (rs.getInt(5)) {
        case Types.STRUCT:
            dataType = new DataType(Types.STRUCT, typeName);
            dataType.setLocalTypeAndParams(structName, null);
            break;
        case Types.DISTINCT:
            dataType = new DataType(Types.DISTINCT, typeName);
            dataType.setLocalTypeAndParams(distinctName, null);
            break;
        case Types.JAVA_OBJECT:
            dataType = new DataType(Types.JAVA_OBJECT, typeName);
            dataType.setLocalTypeAndParams(javaName, null);
            break;
        }
        dataTypes.add(dataType);
    }

    return dataTypes;
}

From source file:com.alibaba.dubbo.governance.status.DatabaseStatusChecker.java

public Status check() {
    boolean ok;//  ww w .  ja va 2  s.c o m
    try {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getTypeInfo();
            try {
                ok = resultSet.next();
            } finally {
                resultSet.close();
            }
            if (message == null) {
                message = metaData.getURL() + " (" + metaData.getDatabaseProductName() + " "
                        + metaData.getDatabaseProductVersion() + ", "
                        + getIsolation(metaData.getDefaultTransactionIsolation()) + ")";
            }
            if (version == 0) {
                version = metaData.getDatabaseMajorVersion();
            }
        } finally {
            connection.close();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        ok = false;
    }
    return new Status(!ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message);
}

From source file:com.qubole.quark.plugins.jdbc.JdbcDB.java

protected ImmutableMap<String, Integer> getTypes(Connection connection) throws SQLException {
    DatabaseMetaData databaseMetaData = connection.getMetaData();
    ResultSet rs = databaseMetaData.getTypeInfo();
    ImmutableMap.Builder<String, Integer> builder = new ImmutableMap.Builder<>();
    while (rs.next()) {
        LOG.debug("Registering data type '" + rs.getString("TYPE_NAME") + "'");
        builder.put(rs.getString("TYPE_NAME").toUpperCase(), rs.getInt("DATA_TYPE"));
    }/* w w w  .  j a  v a2 s . c om*/

    return builder.build();
}

From source file:net.certifi.audittablegen.GenericDMR.java

public Map<String, DataTypeDef> getDataTypes() {

    if (this.dataTypes != null) {
        return this.dataTypes;
    }/*from w w w.  j ava  2s .c o m*/

    //this is kind of ugly.  Some databases (postgres) return the VALUES of
    //metadata in lowercase, while others (hsqldb) return the VALUES of
    //metadata in uppercase.  This is why the key values are stored as
    //case insensitive - so it will work with default types for 
    Map<String, DataTypeDef> types = new CaseInsensitiveMap();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getTypeInfo();

        if (!rs.isBeforeFirst()) {
            throw new RuntimeException("No results for DatabaseMetaData.getTypeInfo()");
        }
        while (rs.next()) {

            DataTypeDef dtd = new DataTypeDef();

            dtd.type_name = rs.getString("TYPE_NAME");
            dtd.data_type = rs.getInt("DATA_TYPE");
            dtd.precision = rs.getInt("PRECISION");
            dtd.literal_prefix = rs.getString("LITERAL_PREFIX");
            dtd.literal_suffix = rs.getString("LITERAL_SUFFIX");
            dtd.create_params = rs.getString("CREATE_PARAMS");
            dtd.nullable = rs.getShort("NULLABLE");
            dtd.case_sensitive = rs.getBoolean("CASE_SENSITIVE");
            dtd.searchable = rs.getShort("SEARCHABLE");
            dtd.unsigned_attribute = rs.getBoolean("UNSIGNED_ATTRIBUTE");
            dtd.fixed_prec_scale = rs.getBoolean("FIXED_PREC_SCALE");
            dtd.auto_increment = rs.getBoolean("AUTO_INCREMENT");
            dtd.local_type_name = rs.getString("LOCAL_TYPE_NAME");
            dtd.minimum_scale = rs.getShort("MINIMUM_SCALE");
            dtd.maximum_scale = rs.getShort("MAXIMUM_SCALE");
            dtd.sql_data_type = rs.getInt("SQL_DATA_TYPE"); //not used
            dtd.sql_datetime_sub = rs.getInt("SQL_DATETIME_SUB"); //not used
            dtd.num_prec_radix = rs.getInt("NUM_PREC_RADIX");

            //google guava primitive types tools
            if (Ints.contains(DataTypeDef.sqlSizedTypes, dtd.data_type) && !dtd.type_name.equals("text")) {
                dtd.createWithSize = true;
            }

            types.put(dtd.type_name, dtd);

        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    this.dataTypes = types;

    Collection<String> debugValues = types.keySet();
    for (String debugValue : debugValues) {
        logger.debug("DB has type value {}", debugValue);

    }

    return types;

}

From source file:com.manydesigns.portofino.model.database.ConnectionProvider.java

public void init(DatabasePlatformsRegistry databasePlatformsRegistry) {
    Connection conn = null;/*from   w w w  .ja va 2s  .  c  om*/
    ResultSet typeRs = null;
    String databaseName = getDatabase().getDatabaseName();
    try {
        conn = acquireConnection();

        DatabaseMetaData metadata = conn.getMetaData();

        databaseProductName = metadata.getDatabaseProductName();
        databaseProductVersion = metadata.getDatabaseProductVersion();

        try {
            databaseMajorVersion = metadata.getDatabaseMajorVersion();
            databaseMinorVersion = metadata.getDatabaseMinorVersion();
            databaseMajorMinorVersion = MessageFormat.format("{0}.{1}", databaseMajorVersion,
                    databaseMinorVersion);
        } catch (SQLException e) {
            databaseMajorMinorVersion = e.getMessage();
        }

        driverName = metadata.getDriverName();
        driverVersion = metadata.getDriverVersion();

        driverMajorVersion = metadata.getDriverMajorVersion();
        driverMinorVersion = metadata.getDriverMinorVersion();
        driverMajorMinorVersion = MessageFormat.format("{0}.{1}", driverMajorVersion, driverMinorVersion);

        try {
            JDBCMajorVersion = metadata.getJDBCMajorVersion();
            JDBCMinorVersion = metadata.getJDBCMinorVersion();
            JDBCMajorMinorVersion = MessageFormat.format("{0}.{1}", JDBCMajorVersion, JDBCMinorVersion);
        } catch (Throwable e) {
            JDBCMajorMinorVersion = e.getMessage();
        }

        // extract supported types
        types.clear();
        typeRs = metadata.getTypeInfo();
        while (typeRs.next()) {
            readType(typeRs);
        }
        fixMissingTypeAliases(types);
        Collections.sort(types, new TypeComparator());

        databasePlatform = databasePlatformsRegistry.findApplicableAbstraction(this);
        if (databasePlatform == null) {
            status = STATUS_ERROR;
            errorMessage = MessageFormat.format("Database platform not found for {0}", databaseProductName);
            logger.warn(errorMessage);
        } else {
            status = STATUS_CONNECTED;
            errorMessage = null;
        }
    } catch (Throwable e) {
        status = STATUS_ERROR;
        errorMessage = e.getMessage();
        logger.warn("Could not create database platform for " + databaseName, e);
    } finally {
        DbUtil.closeResultSetAndStatement(typeRs);
        releaseConnection(conn);
        lastTested = new Date();
    }
}

From source file:jade.domain.DFDBKB.java

/**
 * Returns the name of the SQL type used in the
 * database to represent very long strings.
 *///from w ww .j ava  2 s. c o m
protected String getLongVarCharType() {
    String bestMatch = DEFAULT_LONGVARCHAR_TYPE;
    try {
        // get the datatype with the highest precision from the meta data information
        DatabaseMetaData md = getConnectionWrapper().getConnection().getMetaData();
        ResultSet typeInfo = md.getTypeInfo();
        long maxPrecision = -1;
        while (typeInfo.next()) {
            long jdbcType = Long.parseLong(typeInfo.getString("DATA_TYPE"));
            long precision = Long.parseLong(typeInfo.getString("PRECISION"));

            if (jdbcType == Types.LONGVARCHAR && precision > maxPrecision) {
                maxPrecision = precision;
                bestMatch = typeInfo.getString("TYPE_NAME");
            }
        }
    } catch (SQLException e) {
        // ignored --> default value will be returned
    }
    return bestMatch;
}

From source file:com.netspective.axiom.policy.AnsiDatabasePolicy.java

public void reverseEngineer(Writer writer, Connection conn, String catalog, String schemaPattern)
        throws IOException, SQLException {
    Map dataTypesMap = prepareJdbcTypeInfoMap();
    DatabaseMetaData dbmd = conn.getMetaData();
    TextUtils textUtils = TextUtils.getInstance();

    writer.write("<?xml version=\"1.0\"?>\n\n");
    writer.write("<!-- Reverse engineered by Axiom\n");
    writer.write("     driver: " + dbmd.getDriverName() + "\n");
    writer.write("     driver-version: " + dbmd.getDriverVersion() + "\n");
    writer.write("     product: " + dbmd.getDatabaseProductName() + "\n");
    writer.write("     product-version: " + dbmd.getDatabaseProductVersion() + "\n");

    writer.write("     available catalogs:");
    ResultSet rs = null;//from   w  w  w  . j  a  va2s . com
    try {
        rs = dbmd.getCatalogs();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }

    writer.write("\n");

    writer.write("     available schemas:");
    try {
        rs = dbmd.getSchemas();
        while (rs.next()) {
            writer.write(" " + rs.getObject(1).toString());
        }
    } finally {
        if (rs != null)
            rs.close();
    }
    writer.write("\n");
    writer.write("-->\n\n");

    writer.write("<component xmlns:xdm=\"http://www.netspective.org/Framework/Commons/XMLDataModel\">\n");
    writer.write("    <xdm:include resource=\"com/netspective/axiom/conf/axiom.xml\"/>\n");
    writer.write("    <schema name=\"" + catalog + "." + schemaPattern + "\">\n");

    Map dbmdTypeInfoByName = new HashMap();
    Map dbmdTypeInfoByJdbcType = new HashMap();
    ResultSet typesRS = null;
    try {
        typesRS = dbmd.getTypeInfo();
        while (typesRS.next()) {
            int colCount = typesRS.getMetaData().getColumnCount();
            Object[] typeInfo = new Object[colCount];
            for (int i = 1; i <= colCount; i++)
                typeInfo[i - 1] = typesRS.getObject(i);
            dbmdTypeInfoByName.put(typesRS.getString(1), typeInfo);
            dbmdTypeInfoByJdbcType.put(new Integer(typesRS.getInt(2)), typeInfo);
        }
    } finally {
        if (typesRS != null)
            typesRS.close();
    }

    ResultSet tables = null;
    try {
        tables = dbmd.getTables(catalog, schemaPattern, null, new String[] { "TABLE" });
        while (tables.next()) {
            String tableNameOrig = tables.getString(3);
            String tableName = textUtils.fixupTableNameCase(tableNameOrig);

            writer.write("        <table name=\"" + tableName + "\">\n");

            Map primaryKeys = new HashMap();
            ResultSet pkRS = null;
            try {
                pkRS = dbmd.getPrimaryKeys(null, null, tableNameOrig);
                while (pkRS.next()) {
                    primaryKeys.put(pkRS.getString(4), pkRS.getString(5));
                }

            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (pkRS != null)
                    pkRS.close();
            }

            Map fKeys = new HashMap();
            ResultSet fkRS = null;
            try {
                fkRS = dbmd.getImportedKeys(null, null, tableNameOrig);
                while (fkRS.next()) {
                    fKeys.put(fkRS.getString(8), textUtils.fixupTableNameCase(fkRS.getString(3)) + "."
                            + fkRS.getString(4).toLowerCase());
                }
            } catch (Exception e) {
                // driver may not support this function
            } finally {
                if (fkRS != null)
                    fkRS.close();
            }

            // we keep track of processed columns so we don't duplicate them in the XML
            Set processedColsMap = new HashSet();
            ResultSet columns = null;
            try {
                columns = dbmd.getColumns(null, null, tableNameOrig, null);
                while (columns.next()) {
                    String columnNameOrig = columns.getString(4);
                    if (processedColsMap.contains(columnNameOrig))
                        continue;
                    processedColsMap.add(columnNameOrig);

                    String columnName = columnNameOrig.toLowerCase();

                    writer.write("            <column name=\"" + columnName + "\"");
                    try {
                        if (fKeys.containsKey(columnNameOrig))
                            writer.write(" lookup-ref=\"" + fKeys.get(columnNameOrig) + "\"");
                        else {
                            short jdbcType = columns.getShort(5);
                            String dataType = (String) dataTypesMap.get(new Integer(jdbcType));
                            if (dataType == null)
                                dataType = Short.toString(jdbcType);
                            writer.write(" type=\"" + dataType + "\"");
                        }

                        if (primaryKeys.containsKey(columnNameOrig))
                            writer.write(" primary-key=\"yes\"");

                        if (columns.getString(18).equals("NO"))
                            writer.write(" required=\"yes\"");

                        String defaultValue = columns.getString(13);
                        if (defaultValue != null)
                            writer.write(" default=\"" + defaultValue + "\"");

                        String remarks = columns.getString(12);
                        if (remarks != null)
                            writer.write(" descr=\"" + remarks + "\"");

                    } catch (Exception e) {
                    }

                    writer.write("/>\n");
                }
            } finally {
                if (columns != null)
                    columns.close();
            }

            writer.write("        </table>\n");
        }
    } finally {
        tables.close();
    }

    writer.write("    </schema>\n");
    writer.write("</component>");
}