Example usage for java.sql ResultSetMetaData getColumnTypeName

List of usage examples for java.sql ResultSetMetaData getColumnTypeName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnTypeName.

Prototype

String getColumnTypeName(int column) throws SQLException;

Source Link

Document

Retrieves the designated column's database-specific type name.

Usage

From source file:io.lightlink.oracle.AbstractOracleType.java

protected STRUCT createStruct(Connection con, Object value, String type) throws SQLException {

    if (value == null)
        return null;

    Map mapValue;//from w ww. j a v  a2s.  com
    if (value instanceof Map) {
        mapValue = (Map) value;
        mapValue = new CaseInsensitiveMap(mapValue);
    } else { // create a Map from bean
        Map map = new CaseInsensitiveMap(new BeanMap(value));
        map.remove("class");
        mapValue = map;
    }

    STRUCT struct;
    StructDescriptor structType = safeCreateStructureDescriptor(type, con);
    ResultSetMetaData stuctMeteData = structType.getMetaData();

    List<Object> orderedValues = new ArrayList<Object>();

    if (stuctMeteData.getColumnCount() == 1 && mapValue.size() == 1) {
        orderedValues.add(mapValue.values().iterator().next());
    } else {
        for (int col = 1; col <= stuctMeteData.getColumnCount(); col++) {
            Object v = mapValue.get(stuctMeteData.getColumnName(col));
            if (v == null) {
                v = mapValue.get(stuctMeteData.getColumnName(col).replaceAll("_", ""));
            }

            String typeName = stuctMeteData.getColumnTypeName(col);
            int columnType = stuctMeteData.getColumnType(col);
            if (columnType == OracleTypes.ARRAY) {
                v = createArray(con, v, typeName);
            } else if (columnType == OracleTypes.JAVA_STRUCT || columnType == OracleTypes.JAVA_OBJECT
                    || columnType == OracleTypes.STRUCT) {
                v = createStruct(con, v, typeName);
            }

            orderedValues.add(v);
        }
    }

    Object[] values = orderedValues.toArray();

    for (int j = 0; j < values.length; j++) {

        Object v = values[j];
        if (v instanceof Long && stuctMeteData.getColumnTypeName(j + 1).equalsIgnoreCase("TIMESTAMP")) {
            values[j] = new Timestamp((Long) v);
        } else if (v instanceof Long && stuctMeteData.getColumnTypeName(j + 1).equalsIgnoreCase("DATE")) {
            values[j] = new Date((Long) v);
        }

    }

    struct = new STRUCT(structType, con, values);

    return struct;
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

/**
 *
 *///from   ww  w  . j a  v  a2  s .  c  o m
private Integer getColumnIndex(JRField field) throws JRException {
    String fieldName = field.getName();
    Integer columnIndex = columnIndexMap.get(fieldName);
    if (columnIndex == null) {
        try {
            columnIndex = searchColumnByName(field);

            if (columnIndex == null) {
                columnIndex = searchColumnByLabel(field);
            }

            if (columnIndex == null) {
                columnIndex = searchColumnByIndex(field);
            }

            if (columnIndex == null) {
                columnIndex = searchColumnByName(fieldName);
            }

            if (columnIndex == null) {
                columnIndex = searchColumnByLabel(fieldName);
            }

            if (columnIndex == null && fieldName.startsWith(INDEXED_COLUMN_PREFIX)) {
                columnIndex = searchColumnByIndex(fieldName.substring(INDEXED_COLUMN_PREFIX_LENGTH));
            }

            if (columnIndex == null) {
                throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_UNKNOWN_COLUMN_NAME,
                        new Object[] { fieldName });
            }
        } catch (SQLException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_METADATA_NOT_RETRIEVED, null, e);
        }

        if (log.isDebugEnabled()) {
            try {
                ResultSetMetaData metaData = resultSet.getMetaData();
                log.debug("field " + fieldName + " has type " + metaData.getColumnType(columnIndex) + "/"
                        + metaData.getColumnTypeName(columnIndex) + ", class "
                        + metaData.getColumnClassName(columnIndex));
            } catch (SQLException e) {
                log.debug("failed to read result set metadata", e);
            }
        }

        columnIndexMap.put(fieldName, columnIndex);
    }

    return columnIndex;
}

From source file:com.mvdb.etl.dao.impl.JdbcGenericDAO.java

@Override
public void fetchMetadata(String objectName, File snapshotDirectory) {
    final Metadata metadata = new Metadata();
    metadata.setTableName(objectName);/* www .j a  v  a  2 s. c  om*/
    String sql = "SELECT * FROM " + objectName + " limit 1";
    final Map<String, ColumnMetadata> metaDataMap = new HashMap<String, ColumnMetadata>();
    metadata.setColumnMetadataMap(metaDataMap);
    metadata.setTableName(objectName);

    getJdbcTemplate().query(sql, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet row) throws SQLException {
            ResultSetMetaData rsm = row.getMetaData();
            int columnCount = rsm.getColumnCount();
            for (int column = 1; column < (columnCount + 1); column++) {
                ColumnMetadata columnMetadata = new ColumnMetadata();
                columnMetadata.setColumnLabel(rsm.getColumnLabel(column));
                columnMetadata.setColumnName(rsm.getColumnName(column));
                columnMetadata.setColumnType(rsm.getColumnType(column));
                columnMetadata.setColumnTypeName(rsm.getColumnTypeName(column));

                metaDataMap.put(rsm.getColumnName(column), columnMetadata);
            }

        }
    });

    writeMetadata(metadata, snapshotDirectory);
}

From source file:com.hexin.core.dao.BaseDaoSupport.java

@Override
public <T> List<T> findListWithBlob(String sql, Class<T> dtoClass, Object... args)
        throws SQLException, InstantiationException, IllegalAccessException, SecurityException,
        IllegalArgumentException, NoSuchFieldException, IOException {

    long startTime = System.currentTimeMillis();
    long endTime;
    long durTime;

    debugSql(sql, args);/*from   www  .  java  2  s.c  o m*/

    PreparedStatement ps = jdbcTemplate.getDataSource().getConnection().prepareStatement(sql);

    setPreparedStatementParameter(ps, args);

    List<T> list = new ArrayList<T>();
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();

        T obj = dtoClass.newInstance();
        for (int i = 1; i <= colCount; i++) {
            String colName = rsmd.getColumnLabel(i); // ??
            String colTypeName = rsmd.getColumnTypeName(i);
            String beanFiledName = IcpObjectUtil.underlineToCamel(colName);

            if ("blob".equalsIgnoreCase(colTypeName)) {
                InjectValueUtil.setFieldValue(obj, beanFiledName, rs.getBlob(i));
            } else {
                InjectValueUtil.setFieldValue(obj, beanFiledName, rs.getObject(i));
            }
        }

        list.add(obj);
    }

    endTime = System.currentTimeMillis();
    durTime = endTime - startTime;
    logger.debug("This jdbc operation costs time: " + durTime);

    return list;
}

From source file:org.apache.kylin.rest.adhoc.AdHocRunnerJdbcImpl.java

@Override
public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas)
        throws Exception {
    Statement statement = null;/*from   w w w .ja  va2s  .c  om*/
    Connection connection = this.getConnection();
    ResultSet resultSet = null;

    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);
        extractResults(resultSet, results);
    } catch (SQLException sqlException) {
        throw sqlException;
    }

    //extract column metadata
    ResultSetMetaData metaData = null;
    int columnCount = 0;
    try {
        metaData = resultSet.getMetaData();
        columnCount = metaData.getColumnCount();

        // fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                    false, metaData.isCurrency(i), metaData.isNullable(i), false,
                    metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i),
                    null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i),
                    metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false));
        }

    } catch (SQLException sqlException) {
        throw sqlException;
    }

    closeConnection(connection);
}

From source file:org.glom.web.server.database.RelatedListNavigation.java

public NavigationRecord getNavigationRecord(final TypedDataItem primaryKeyValue) {

    if (portal == null) {
        Log.error(documentID, tableName,
                "The related list navigation cannot be determined because the LayoutItemPortal has not been found.");
        return null;
    }//from  w  w w .  jav  a2 s. c  o m

    if (primaryKeyValue == null) {
        Log.error(documentID, tableName,
                "The related list navigation cannot be determined because the primaryKeyValue is null.");
        return null;
    }

    final TableToViewDetails navigationTable = document.getPortalSuitableTableToViewDetails(portal);
    if (navigationTable == null) {
        Log.error(documentID, tableName,
                "The related list navigation cannot cannot be determined because the navigation table details are empty.");
        return null;
    }

    if (StringUtils.isEmpty(navigationTable.tableName)) {
        Log.error(documentID, tableName,
                "The related list navigation cannot cannot be determined because the navigation table name is empty.");
        return null;
    }

    // Get the primary key of that table:
    final Field navigationTablePrimaryKey = document.getTablePrimaryKeyField(navigationTable.tableName);

    // Build a layout item to get the field's value:
    final LayoutItemField navigationRelationshipItem = new LayoutItemField();
    navigationRelationshipItem.setName(navigationTablePrimaryKey.getName());
    navigationRelationshipItem.setFullFieldDetails(navigationTablePrimaryKey);
    if (navigationTable.usesRelationship != null) {
        navigationRelationshipItem.setRelationship(navigationTable.usesRelationship.getRelationship());
        navigationRelationshipItem
                .setRelatedRelationship(navigationTable.usesRelationship.getRelatedRelationship());
    }

    // Get the value of the navigation related primary key:
    final List<LayoutItemField> fieldsToGet = new ArrayList<LayoutItemField>();
    fieldsToGet.add(navigationRelationshipItem);

    // For instance "invoice_line_id" if this is a portal to an "invoice_lines" table:
    final String relatedTableName = portal.getTableUsed("" /* not relevant */);
    final Field primaryKeyField = document.getTablePrimaryKeyField(relatedTableName);
    if (primaryKeyField == null) {
        Log.error(documentID, tableName,
                "The related table's primary key field could not be found, for related table "
                        + relatedTableName);
        return null;
    }

    final NavigationRecord navigationRecord = new NavigationRecord();
    String query = null;
    ResultSet rs = null;
    try {
        if (primaryKeyValue != null) {

            // Make sure that the value knows its actual type,
            // in case it was received via a URL parameter as a string representation:
            Utils.transformUnknownToActualType(primaryKeyValue, primaryKeyField.getGlomType());

            query = SqlUtils.buildSqlSelectWithKey(relatedTableName, fieldsToGet, primaryKeyField,
                    primaryKeyValue, document.getSqlDialect());

            rs = SqlUtils.executeQuery(cpds, query);

            // Set the output parameters:
            navigationRecord.setTableName(navigationTable.tableName);

            rs.next();
            final TypedDataItem navigationTablePrimaryKeyValue = new TypedDataItem();
            final ResultSetMetaData rsMetaData = rs.getMetaData();
            final int queryReturnValueType = rsMetaData.getColumnType(1);
            switch (navigationTablePrimaryKey.getGlomType()) {
            case TYPE_NUMERIC:
                if (queryReturnValueType == java.sql.Types.NUMERIC) {
                    navigationTablePrimaryKeyValue.setNumber(rs.getDouble(1));
                } else {
                    logNavigationTablePrimaryKeyTypeMismatchError(Field.GlomFieldType.TYPE_NUMERIC,
                            rsMetaData.getColumnTypeName(1));
                }
                break;
            case TYPE_TEXT:
                if (queryReturnValueType == java.sql.Types.VARCHAR) {
                    navigationTablePrimaryKeyValue.setText(rs.getString(1));
                } else {
                    logNavigationTablePrimaryKeyTypeMismatchError(Field.GlomFieldType.TYPE_TEXT,
                            rsMetaData.getColumnTypeName(1));
                }
                break;
            default:
                Log.error(documentID, tableName,
                        "Unsupported java.sql.Type: " + rsMetaData.getColumnTypeName(1));
                Log.error(documentID, tableName,
                        "The navigation table primary key value will not be created. This is a bug.");
                break;
            }

            // The value is empty when there there is no record to match the key in the related table:
            // For instance, if an invoice lines record mentions a product id, but the product does not exist in the
            // products table.
            if (navigationTablePrimaryKeyValue.isEmpty()) {
                Log.info(documentID, tableName, "SQL query returned empty primary key for navigation to the "
                        + navigationTable.tableName + "table. Navigation may not work correctly");
                navigationRecord.setPrimaryKeyValue(null);
            } else {
                navigationRecord.setPrimaryKeyValue(navigationTablePrimaryKeyValue);
            }
        }
    } catch (final SQLException e) {
        Log.error(documentID, tableName, "Error executing database query: " + query, e);
        // TODO: somehow notify user of problem
        return null;
    } finally {
        // cleanup everything that has been used
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (final Exception e) {
            Log.error(documentID, tableName,
                    "Error closing database resources. Subsequent database queries may not work.", e);
        }
    }

    return navigationRecord;
}

From source file:com.mapd.utility.SQLImporter.java

private void createMapDTable(ResultSetMetaData metaData) {

    StringBuilder sb = new StringBuilder();
    sb.append("Create table ").append(cmd.getOptionValue("targetTable")).append("(");

    // Now iterate the metadata
    try {/*  w  ww. j  a va2  s .c om*/
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            if (i > 1) {
                sb.append(",");
            }
            LOGGER.debug("Column name is " + metaData.getColumnName(i));
            LOGGER.debug("Column type is " + metaData.getColumnTypeName(i));
            LOGGER.debug("Column type is " + metaData.getColumnType(i));

            sb.append(metaData.getColumnName(i)).append(" ");

            sb.append(getColType(metaData.getColumnType(i), metaData.getPrecision(i), metaData.getScale(i)));
        }
        sb.append(")");

        if (Integer.valueOf(cmd.getOptionValue("fragmentSize", "0")) > 0) {
            sb.append(" with (fragment_size = ");
            sb.append(cmd.getOptionValue("fragmentSize", "0"));
            sb.append(")");
        }

    } catch (SQLException ex) {
        LOGGER.error("Error processing the metadata - " + ex.toString());
        exit(1);
    }

    executeMapDCommand(sb.toString());

}

From source file:com.waveerp.systemDBDirect.java

public ArrayList loadTableEntries() {

    // Added by Jammi Dee 05/03/2012
    registrySystem rss = new registrySystem();

    url = rss.readRegistry("NA", "NA", "NA", "DBURL");
    dbName = rss.readRegistry("NA", "NA", "NA", "DBDATABASE");
    driver = rss.readRegistry("NA", "NA", "NA", "DBDRIVER");
    user = rss.readRegistry("NA", "NA", "NA", "DBUSER");
    password = rss.readRegistry("NA", "NA", "NA", "DBPASSWORD");

    // Added by Jammi Dee 05/03/2012
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    ArrayList trList = new ArrayList();

    try {/*w w w.  j a  v  a2s.  c  o  m*/
        Class.forName(getDriver());
        con = DriverManager.getConnection(url + dbName, user, password);
        ps = con.createStatement();

        rs = ps.executeQuery(querystring);

        /////////////////////////////////////////////
        // Get the number of columns here. I need
        // this to add dynaminism to my table loader
        /////////////////////////////////////////////
        ResultSetMetaData rsmd = rs.getMetaData();
        setColCount(rsmd.getColumnCount());

        ///////////////////////////////////////////
        // Load the column types to an array
        // Never access it directly, java simply
        // returns NULL, whew I don't know why
        ///////////////////////////////////////////
        String[] colTypes = new String[colCount];
        for (int j = 0; j <= getColCount() - 1; j++) {
            colTypes[j] = rsmd.getColumnTypeName(j + 1);
        }

        while (rs.next()) {

            //System.out.println(rs.getString(1));
            String[] item = new String[colCount];

            for (int j = 0; j < getColCount(); j++) {

                if (colTypes[j] == "VARCHAR") {
                    item[j] = rs.getString(j + 1);
                }
                if (colTypes[j] == "VARCHAR2") {
                    item[j] = rs.getString(j + 1);
                }
                if (colTypes[j] == "NUMBER") {
                    item[j] = Double.toString(rs.getDouble(j + 1));
                }
                if (colTypes[j] == "DATE") {
                    item[j] = rs.getDate(j + 1).toString();
                }
                if (colTypes[j] == "DATETIME") {
                    item[j] = colTypes[j]; // lrs.getTimestamp(j+1).toString();
                }
                if (colTypes[j] == "TIMESTAMP") {
                    item[j] = colTypes[j];
                }

            }

            trList.add(item);

        }

        ps.close();
        con.close();

    } catch (Exception e) {

        //System.out.println(e.getMessage());
        e.printStackTrace();

    }

    return trList;
}

From source file:com.waveerp.jsonLibrary02.java

public String loadDataEntries() {

    // Added by Jammi Dee 05/03/2012
    registrySystem rss = new registrySystem();
    url = rss.readRegistry("NA", "NA", "NA", "DBURL");
    dbName = rss.readRegistry("NA", "NA", "NA", "DBDATABASE");
    driver = rss.readRegistry("NA", "NA", "NA", "DBDRIVER");
    user = rss.readRegistry("NA", "NA", "NA", "DBUSER");
    password = rss.readRegistry("NA", "NA", "NA", "DBPASSWORD");

    // Added by Jammi Dee 05/03/2012
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    try {//from   w ww.  j a v a  2  s .co  m
        Class.forName(getDriver());
        con = DriverManager.getConnection(url + dbName, user, password);
        ps = con.createStatement();

        rs = ps.executeQuery(querystring);

        /////////////////////////////////////////////
        // Get the number of columns here. I need
        // this to add dynaminism to my table loader
        /////////////////////////////////////////////
        ResultSetMetaData rsmd = rs.getMetaData();
        setColCount(rsmd.getColumnCount());

        ///////////////////////////////////////////
        // Load the column types to an array
        // Never access it directly, java simply
        // returns NULL, whew I don't know why
        ///////////////////////////////////////////
        String[] colTypes = new String[colCount];
        for (int j = 0; j <= getColCount() - 1; j++) {
            colTypes[j] = rsmd.getColumnTypeName(j + 1);
        }

        /**
         * Initialize the working arrays here for the process
         * Added by Jammi Dee 06/06/2012
        */
        while (rs.next()) {
            String id = rs.getString(1);
        }
        rs.last();
        int rowCount = rs.getRow();
        nodeid = new String[rowCount];
        nodedesc = new String[rowCount];
        nodeparent = new String[rowCount];

        int ipoint = 0;
        rs.beforeFirst();

        while (rs.next()) {

            nodeid[ipoint] = rs.getString(1);
            nodedesc[ipoint] = rs.getString(2);
            nodeparent[ipoint] = rs.getString(3);

            // Increment the pointer
            ipoint = ipoint + 1;

        }

        ps.close();
        con.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        return "FAILED";

    }

    return "SUCCESS";
}

From source file:com.kylinolap.query.test.KylinTestBase.java

protected int output(ResultSet resultSet, boolean needDisplay) throws SQLException {
    int count = 0;
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();
    StringBuilder sb = new StringBuilder("\n");
    if (needDisplay) {
        for (int i = 1; i <= columnCount; i++) {
            sb.append(metaData.getColumnName(i));
            sb.append("-");
            sb.append(metaData.getTableName(i));
            sb.append("-");
            sb.append(metaData.getColumnTypeName(i));
            if (i < columnCount) {
                sb.append("\t");
            } else {
                sb.append("\n");
            }/*www .j a va2s  . co m*/
        }
    }

    while (resultSet.next()) {
        if (needDisplay) {
            for (int i = 1; i <= columnCount; i++) {
                sb.append(resultSet.getString(i));
                if (i < columnCount) {
                    sb.append("\t");
                } else {
                    sb.append("\n");
                }
            }
        }
        count++;
    }
    printInfo(sb.toString());
    return count;
}