Example usage for java.sql ResultSetMetaData getColumnType

List of usage examples for java.sql ResultSetMetaData getColumnType

Introduction

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

Prototype

int getColumnType(int column) throws SQLException;

Source Link

Document

Retrieves the designated column's SQL type.

Usage

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the most appropriate
 * value type. The returned value should be a detached value object, not
 * having any ties to the active ResultSet: in particular, it should not be
 * a Blob or Clob object but rather a byte array respectively String
 * representation.//from   w w w.j av a  2s  .  com
 * <p>
 * Uses the <code>getObject(index)</code> method, but includes additional
 * "hacks" to get around Oracle 10g returning a non-standard object for its
 * TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
 * leaving out the time portion: These columns will explicitly be extracted
 * as standard <code>java.sql.Timestamp</code> object.
 *
 * @param rs
 *            is the ResultSet holding the data
 * @param index
 *            is the column index
 * @param readStringsAsBytes TODO
 * @return the value object
 * @throws SQLException
 *             if thrown by the JDBC API
 * @see java.sql.Blob
 * @see java.sql.Clob
 * @see java.sql.Timestamp
 */
public static Object getResultSetValue(ResultSet rs, int index, boolean readStringsAsBytes)
        throws SQLException {
    ResultSetMetaData metaData = rs.getMetaData();
    Object obj = null;
    int jdbcType = metaData.getColumnType(index);
    if (readStringsAsBytes && TypeMap.isTextType(jdbcType)) {
        byte[] bytes = rs.getBytes(index);
        if (bytes != null) {
            obj = new String(bytes);
        }
    } else {
        obj = rs.getObject(index);
    }
    String className = null;
    if (obj != null) {
        className = obj.getClass().getName();
    }
    if (obj instanceof Blob) {
        Blob blob = (Blob) obj;
        InputStream is = blob.getBinaryStream();
        try {
            obj = IOUtils.toByteArray(is);
        } catch (IOException e) {
            throw new SqlException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    } else if (obj instanceof Clob) {
        Clob clob = (Clob) obj;
        Reader reader = clob.getCharacterStream();
        try {
            obj = IOUtils.toString(reader);
        } catch (IOException e) {
            throw new SqlException(e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    } else if (className != null && ("oracle.sql.TIMESTAMP".equals(className))) {
        obj = rs.getTimestamp(index);
    } else if (className != null && "oracle.sql.TIMESTAMPTZ".equals(className)) {
        obj = rs.getString(index);
    } else if (className != null && "oracle.sql.TIMESTAMPLTZ".equals(className)) {
        obj = rs.getString(index);
    } else if (className != null && className.startsWith("oracle.sql.DATE")) {
        String metaDataClassName = metaData.getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj instanceof java.sql.Date) {
        String metaDataClassName = metaData.getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        }
    } else if (obj instanceof Timestamp) {
        String typeName = metaData.getColumnTypeName(index);
        if (typeName != null && typeName.equals("timestamptz")) {
            obj = rs.getString(index);
        }
    }
    return obj;
}

From source file:org.tinygroup.tinydb.util.TinyBeanUtil.java

public static List<Field> getFieldsWithResultSet(ResultSet rs, BeanDbNameConverter converter)
        throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    List<Field> fields = new ArrayList<Field>();
    Map<String, Integer> columnViewnum = new HashMap<String, Integer>();
    for (int index = 1; index <= columnCount; index++) {
        String columnName = JdbcUtils.lookupColumnName(rsmd, index);
        String propertyName = converter.dbFieldNameToPropertyName(columnName);
        String name = propertyName;
        if (!columnViewnum.containsKey(propertyName)) {
            columnViewnum.put(propertyName, 1);
        } else {/*from  www. j  a v a  2  s .  c  o m*/
            int number = columnViewnum.get(propertyName);
            name = propertyName + number;
            columnViewnum.put(propertyName, number++);
        }
        Field field = new Field();
        field.setName(name);
        field.setIndex(index);
        field.setPrecision(rsmd.getPrecision(index));
        field.setScale(rsmd.getScale(index));
        field.setType(rsmd.getColumnType(index));
        fields.add(field);
    }
    return fields;
}

From source file:com.healthmarketscience.jackcess.ImportUtil.java

/**
 * Copy an existing JDBC ResultSet into a new (or optionally existing) table
 * in this database./* ww  w. j  a va 2s . co m*/
 * 
 * @param name Name of the new table to create
 * @param source ResultSet to copy from
 * @param filter valid import filter
 * @param useExistingTable if {@code true} use current table if it already
 *                         exists, otherwise, create new table with unique
 *                         name
 *
 * @return the name of the imported table
 * 
 * @see Builder
 */
public static String importResultSet(ResultSet source, Database db, String name, ImportFilter filter,
        boolean useExistingTable) throws SQLException, IOException {
    ResultSetMetaData md = source.getMetaData();

    name = Database.escapeIdentifier(name);
    Table table = null;
    if (!useExistingTable || ((table = db.getTable(name)) == null)) {

        List<Column> columns = new LinkedList<Column>();
        for (int i = 1; i <= md.getColumnCount(); i++) {
            Column column = new Column();
            column.setName(Database.escapeIdentifier(md.getColumnName(i)));
            int lengthInUnits = md.getColumnDisplaySize(i);
            column.setSQLType(md.getColumnType(i), lengthInUnits);
            DataType type = column.getType();
            // we check for isTrueVariableLength here to avoid setting the length
            // for a NUMERIC column, which pretends to be var-len, even though it
            // isn't
            if (type.isTrueVariableLength() && !type.isLongValue()) {
                column.setLengthInUnits((short) lengthInUnits);
            }
            if (type.getHasScalePrecision()) {
                int scale = md.getScale(i);
                int precision = md.getPrecision(i);
                if (type.isValidScale(scale)) {
                    column.setScale((byte) scale);
                }
                if (type.isValidPrecision(precision)) {
                    column.setPrecision((byte) precision);
                }
            }
            columns.add(column);
        }

        table = createUniqueTable(db, name, columns, md, filter);
    }

    List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE);
    int numColumns = md.getColumnCount();

    while (source.next()) {
        Object[] row = new Object[numColumns];
        for (int i = 0; i < row.length; i++) {
            row[i] = source.getObject(i + 1);
        }
        row = filter.filterRow(row);
        if (row == null) {
            continue;
        }
        rows.add(row);
        if (rows.size() == COPY_TABLE_BATCH_SIZE) {
            table.addRows(rows);
            rows.clear();
        }
    }
    if (rows.size() > 0) {
        table.addRows(rows);
    }

    return table.getName();
}

From source file:com.google.visualization.datasource.util.SqlDataSourceHelper.java

/**
 * Returns the table description which includes the ids, labels and types of
 * the table columns.//w  ww. j a  va2 s  .  c  o  m
 *
 * @param rs The result set holding the data from the sql table.
 * @param columnIdsList The list of the column ids in the data table.
 *
 * @return The table description.
 *
 * @throws SQLException Thrown when the connection to the database failed.
 */
static DataTable buildColumns(ResultSet rs, List<String> columnIdsList) throws SQLException {
    DataTable result = new DataTable();
    ResultSetMetaData metaData = rs.getMetaData();
    int numOfCols = metaData.getColumnCount();
    // For each column in the table, create the column description. SQL indexes
    // are 1-based.
    for (int i = 1; i <= numOfCols; i++) {
        String id = (columnIdsList == null) ? metaData.getColumnLabel(i) : columnIdsList.get(i - 1);
        ColumnDescription columnDescription = new ColumnDescription(id,
                sqlTypeToValueType(metaData.getColumnType(i)), metaData.getColumnLabel(i));
        result.addColumn(columnDescription);
    }
    return result;
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.FileSizeResourcesConversionHandler.java

public Object getSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    String rv = null;/*from w ww.j  a  v a  2s  . c  o m*/
    switch (metadata.getColumnType(1)) {
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length());
        }
        break;
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        rv = rs.getString(1);
        break;
    }
    return rv;
}

From source file:com.quest.orahive.HiveJdbcClient.java

private static List<OracleTableColumn> getOracleTableColumnsForHiveResults(ResultSet resultSet) {

    List<OracleTableColumn> result = null;

    try {//from   w  w w. ja v  a2 s  . co m
        ResultSetMetaData metaData = resultSet.getMetaData();

        result = new ArrayList<OracleTableColumn>(metaData.getColumnCount());

        for (int idx = 0; idx < metaData.getColumnCount(); idx++) {
            OracleTableColumn column = new OracleTableColumn();
            result.add(column);

            // column Name...
            column.setName(metaData.getColumnLabel(idx + 1)); //<- 1-based in JDBC;

            // Sql Type...
            column.sqlType = metaData.getColumnType(idx + 1); //<- 1-based in JDBC

            // column Oracle data-type...

            Constants.OracleType oracleType = javaSqlTypeToOracleType(column.sqlType);

            switch (oracleType) {

            case VARCHAR2: {

                column.oracleDataType = String.format("%s(%d)", oracleType.toString(), 4000 // Max length for a varchar
                );
                break;
            }

            default: {
                column.oracleDataType = oracleType.toString();
                break;
            }

            }
        }

    } catch (SQLException ex) {
        LOG.error("An error occurred when processing the metadata for the Hive result-set.", ex);
        System.exit(1);
    }

    return result;
}

From source file:com.trackplus.ddl.GenericStringValueConverter.java

@Override
public String getStringValue(ResultSetMetaData rsmd, int idx, ResultSet rs, String tableName)
        throws SQLException, DDLException {
    String value = null;//from w ww.ja  v a2  s  . co m
    int type = rsmd.getColumnType(idx);
    String columnName = rsmd.getColumnName(idx);
    if (tableName.equalsIgnoreCase("TSITE") && columnName.equalsIgnoreCase("EXPDATE")) {
        Date d = rs.getDate(idx);
        if (d != null) {
            value = "'" + d + "'";
        }
    } else {
        value = extractColumnValue(rs, idx, type);
    }
    return value;
}

From source file:org.sakaiproject.mailarchive.impl.conversion.ExtractXMLToColumns.java

public Object getSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    String rv = null;/*  ww w .  j  a  v a2  s. c  om*/
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            rv = new String(blob.getBytes(1L, (int) blob.length()));
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length());
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        byte[] bytes = rs.getBytes(1);
        if (bytes != null) {
            rv = new String(bytes);
        }
        break;
    }
    // System.out.println("getSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:org.sakaiproject.mailarchive.impl.conversion.ExtractXMLToColumns.java

public Object getValidateSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    byte[] rv = null;
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            rv = blob.getBytes(1L, (int) blob.length());
        } else {//from   w w w. j  av a  2s.  co  m
            System.out.println("getValidateSource(" + id + ") blob ==  null");
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length()).getBytes();
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        rv = rs.getString(1).getBytes();
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        rv = rs.getBytes(1);
        break;
    }
    // System.out.println("getValidateSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static boolean isClobType(final ResultSet rs, final int colNum, final ResultSetMetaData rsmeta)
        throws SQLException {
    switch (rsmeta.getColumnType(colNum)) {
    case Types.CLOB:
        return true;
    default:// ww w  . j  a  v  a  2  s  .co m
        return false;
    }
}