Example usage for java.sql Types CHAR

List of usage examples for java.sql Types CHAR

Introduction

In this page you can find the example usage for java.sql Types CHAR.

Prototype

int CHAR

To view the source code for java.sql Types CHAR.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type CHAR.

Usage

From source file:com.squid.core.jdbc.formatter.DefaultJDBCDataFormatter.java

public String formatJDBCObject(final Object jdbcObject, final int colType) throws SQLException {
    String value = "";

    switch (colType) {
    case Types.BIT:
        if (jdbcObject != null) {
            value = String.valueOf(jdbcObject);
        }/*  ww w .ja  v  a 2 s.c  om*/
        break;
    case Types.BOOLEAN:
        if (jdbcObject != null) {
            value = new Boolean(jdbcObject.toString()).toString();
        }
        break;
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.REAL:
    case Types.NUMERIC:
        if (jdbcObject != null) {
            value = "" + formatter.formatDecimal(jdbcObject);
        }
        break;
    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
        if (jdbcObject != null) {
            value = "" + formatter.formatDecimal(jdbcObject);
        }
        break;
    case Types.CLOB:
        if (jdbcObject != null) {
            try {
                value = read((Clob) jdbcObject);
            } catch (SQLException sqle) {
                value = "";
            } catch (IOException ioe) {
                value = "";
            }
        }
        break;
    case Types.ARRAY:
        try {
            ResultSet rs = ((Array) jdbcObject).getResultSet();
            int arrayType = ((Array) jdbcObject).getBaseType();
            boolean isNotNew = false;
            while (rs.next()) {
                String current = formatJDBCObject(rs.getObject(2), arrayType);
                if ("".equals(current.trim()) == false) {
                    if (isNotNew) {
                        value = value + ",";
                    } else {
                        isNotNew = !isNotNew;
                    }
                    value = value + current;
                }
            }
            if ("".equals(value) == false) {
                value = "{" + value + "}";
            }
        } catch (SQLException sqle) {
            value = "";
        }
        break;
    case Types.JAVA_OBJECT:
        if (jdbcObject != null) {
            value = String.valueOf(jdbcObject);
        }
        break;
    case Types.DATE:
        if (jdbcObject != null) {
            value = formatter.formatDate(jdbcObject);
        }
        break;
    case Types.TIME:
        if (jdbcObject != null) {
            value = ((Time) jdbcObject).toString();
        }
        break;
    case Types.TIMESTAMP:
        if (jdbcObject != null) {
            value = formatter.formatTimestamp(jdbcObject);
        }
        break;
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
        if (jdbcObject != null) {
            value = jdbcObject.toString();
        } else {
            value = "NULL";
        }
        break;
    case Types.BINARY:
        value = new String((byte[]) jdbcObject);
        break;
    default:
        value = "";
    }
    if (value == null) {
        value = "";
    }
    return value;
}

From source file:org.apache.openjpa.jdbc.schema.Schemas.java

/**
 * Return the java type for the given SQL type from {@link Types}.
 *///from w  w  w  .j a  v a  2  s.c  o m
public static Class<?> getJavaType(int type, int size, int decimals) {
    switch (type) {
    case Types.CHAR:
        if (size == 1)
            return char.class;
        // no break
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.CLOB:
        return String.class;
    case Types.BIT:
        return boolean.class;
    case Types.TINYINT:
        return byte.class;
    case Types.SMALLINT:
        return short.class;
    case Types.INTEGER:
        return int.class;
    case Types.BIGINT:
        return long.class;
    case Types.REAL:
    case Types.FLOAT:
        return float.class;
    case Types.DOUBLE:
    case Types.NUMERIC:
        return double.class;
    case Types.DECIMAL:
        // oracle uses this for everything, so look at size and decimals
        if (decimals == 0 && size < 10)
            return int.class;
        else if (decimals == 0)
            return long.class;
        return double.class;
    // ### return a BigDecimal if the size if out of double range?
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        return Date.class;
    default:
        return Object.class;
    }
}

From source file:madgik.exareme.master.queryProcessor.analyzer.stat.ExternalStat.java

@Override
public Map<String, Table> extractStats() throws Exception {

    DatabaseMetaData dbmd = con.getMetaData(); // dtabase metadata object

    // listing tables and columns
    String catalog = null;//from ww w  .  java 2s  .  c o m
    String schemaPattern = sch;
    String tableNamePattern = tblName;
    String columnNamePattern = "%";
    if (con.getClass().getName().contains("postgresql")) {
        // tableNamePattern="\""+tableNamePattern+"\"";
        schemaPattern = "public";
    }

    // ResultSet resultTables = dbmd.getTables(catalog, "public",
    // tableNamePattern, types);
    ResultSet resultColumns = dbmd.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern);
    if (con.getClass().getName().contains("postgresql")) {
        tableNamePattern = "\"" + tableNamePattern + "\"";
    } else if (con.getClass().getName().contains("oracle")) {
        tableNamePattern = schemaPattern + "." + tableNamePattern;
    }
    log.debug("Starting extracting stats");
    // while (resultTables.next()) {
    Map<String, Column> columnMap = new HashMap<String, Column>();
    // StringEscapeUtils.escapeJava(resultTables.getString(3));
    log.debug("Analyzing table " + tblName);

    int toupleSize = 0; // in bytes

    // tableNamePattern = tableName;

    int columnCount = resultColumns.getMetaData().getColumnCount();
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("select count(*) from " + tableNamePattern);
    int count = 0;
    if (rs.next()) {
        count = rs.getInt(1);
    } else {
        log.error("could not get count for table " + tableNamePattern);
    }
    rs.close();
    st.close();

    ResultSet pkrs = dbmd.getExportedKeys("", "", tblName);
    String pkey = "DEFAULT_KEY";

    while (pkrs.next()) {
        pkey = pkrs.getString("PKCOLUMN_NAME");
        break;
    }
    pkrs.close();
    if (count == 0) {
        log.debug("Empty table");
        Table t = new Table(tblName, columnCount, toupleSize, columnMap, count, pkey);
        schema.put(tblName, t);
        return schema;
    }

    while (resultColumns.next()) {

        String columnName = StringEscapeUtils.escapeJava(resultColumns.getString(4));
        try {
            String colNamePattern = columnName;
            if (con.getClass().getName().contains("postgresql")) {
                colNamePattern = "\"" + columnName + "\"";
            }
            int columnType = resultColumns.getInt(5);

            // computing column's size in bytes
            int columnSize = computeColumnSize(colNamePattern, columnType, tableNamePattern);
            toupleSize += columnSize;

            // execute queries for numberOfDiffValues, minVal, maxVal
            // Map<String, Integer> diffValFreqMap = new HashMap<String,
            // Integer>();

            // computing column's min and max values
            String minVal = "0";
            String maxVal = "0";
            if (columnType != Types.BLOB) {
                MinMax mm = computeMinMax(tableNamePattern, colNamePattern);
                minVal = mm.getMin();
                maxVal = mm.getMax();
            }
            Map<String, Integer> diffValFreqMap = new HashMap<String, Integer>();
            //only for equidepth!

            // for (ValFreq k : freqs) {
            // diffValFreqMap.put(k.getVal(), k.getFreq());

            // }

            // /add min max diff vals in the sampling values

            int minOcc = 1;
            int maxOcc = 1;
            int diffVals = 0;
            boolean equidepth = false;
            if (equidepth) {

                //diffValFreqMap is used only in equidepth, do not compute it
                //if we have primitive
                diffValFreqMap = computeDistinctValuesFrequency(tableNamePattern, colNamePattern);

                String minValChar = minVal;
                String maxValChar = maxVal;
                if (columnType == Types.VARCHAR || columnType == Types.CHAR || columnType == Types.LONGNVARCHAR
                        || columnType == Types.DATE) {
                    minValChar = "\'" + minVal + "\'";
                    maxValChar = "\'" + maxVal + "\'";
                }
                try {
                    minOcc = computeValOccurences(tableNamePattern, colNamePattern, minValChar);
                } catch (Exception e) {
                    log.error("Could not compute value occurences for column:" + colNamePattern + " and value:"
                            + minValChar);
                }
                if (equidepth && !diffValFreqMap.containsKey(minVal))
                    diffValFreqMap.put(minVal, minOcc);

                try {
                    maxOcc = computeValOccurences(tableNamePattern, colNamePattern, maxValChar);
                } catch (Exception e) {
                    log.error("Could not compute value occurences for column:" + colNamePattern + " and value:"
                            + maxValChar);
                }
                if (diffValFreqMap.containsKey(maxVal))
                    diffValFreqMap.put(maxVal, maxOcc);

                diffVals = diffValFreqMap.size();
            } else {
                diffVals = computeDiffVals(tableNamePattern, colNamePattern, columnType);
            }
            if (diffVals == 0) {
                //all values are null!
                continue;
            }
            Column c = new Column(columnName, columnType, columnSize, diffVals, minVal, maxVal, diffValFreqMap);
            columnMap.put(columnName, c);
        } catch (Exception ex) {
            log.error("could not analyze column " + columnName + ":" + ex.getMessage());
        }

    }

    Table t = new Table(tblName, columnCount, toupleSize, columnMap, count, pkey);
    schema.put(tblName, t);

    // }
    // resultTables.close();
    resultColumns.close();
    return schema;

}

From source file:org.apache.openjpa.jdbc.sql.AzureDictionary.java

private Column[] getColumns(final Connection conn, final DBIdentifier schemaName, final DBIdentifier tableName,
        final DBIdentifier columnName) {

    if (DBIdentifier.isNull(tableName) && !supportsNullTableForGetColumns) {
        return null;
    }/*from  ww w .jav  a  2s. com*/

    final String sqlSchema = supportsSchemaForGetColumns ? getSchemaNameForMetadata(schemaName) : null;
    final String sqlTable = getTableNameForMetadata(tableName);
    final String sqlColumn = getColumnNameForMetadata(columnName);

    final List<Column> columnList = new ArrayList<Column>();

    Statement stmt = null;
    ResultSet resultSet = null;
    try {
        stmt = conn.createStatement();
        resultSet = stmt
                .executeQuery("EXEC sp_columns " + sqlTable + ", " + sqlSchema + ", null, " + sqlColumn);

        while (resultSet.next()) {
            final Column column = newColumn(resultSet);
            columnList.add(column);

            // for opta driver, which reports nvarchar as unknown type
            String typeName = column.getTypeIdentifier().getName();
            if (typeName == null) {
                continue;
            }
            typeName = typeName.toUpperCase();

            if ("NVARCHAR".equals(typeName)) {
                column.setType(Types.VARCHAR);
            } else if ("UNIQUEIDENTIFIER".equals(typeName)) {
                if (uniqueIdentifierAsVarbinary) {
                    column.setType(Types.VARBINARY);
                } else {
                    column.setType(Types.VARCHAR);
                }
            } else if ("NCHAR".equals(typeName)) {
                column.setType(Types.CHAR);
            } else if ("NTEXT".equals(typeName)) {
                column.setType(Types.CLOB);
            }
        }
    } catch (SQLException e) {
        log.error("Error getting columns", e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("Error closing result set", e);
            }
        }
        try {
            stmt.close();
        } catch (SQLException e) {
            log.error("Error closing statement", e);
        }
    }

    return (Column[]) columnList.toArray(new Column[columnList.size()]);
}

From source file:org.jamwiki.db.WikiPreparedStatement.java

/**
 * Sets the designated parameter to the given Java character value. The
 * driver converts this to an SQL CHAR value when it sends it to the database.
 *
 * @param parameterIndex The first parameter is 1, the second is 2, ...
 * @param x The parameter value./*from  w w w .j a va 2s.  c o m*/
 * @throws Exception If a parameter is invalid.
 */
public void setChar(int parameterIndex, char x) throws Exception {
    this.verifyParams(parameterIndex);
    this.paramTypes[parameterIndex - 1] = Types.CHAR;
    this.params[parameterIndex - 1] = new Character(x);
}

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  . java  2  s .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:com.squid.core.jdbc.formatter.DefaultJDBCDataFormatter.java

public Object unboxJDBCObject(final Object jdbcObject, final int colType) throws SQLException {
    if (colType == Types.CHAR && jdbcObject != null) {
        return StringUtils.stripEnd((String) jdbcObject, " ");
    }/*from   w w w  .jav  a 2 s .c o m*/
    return jdbcObject;
}

From source file:org.batoo.jpa.jdbc.adapter.HsqlAdaptor.java

/**
 * {@inheritDoc}/*from w w w  . j a v a 2 s .  c  om*/
 * 
 */
@Override
protected String getColumnType(AbstractColumn cd, int sqlType) {
    switch (sqlType) {
    case Types.BLOB:
    case Types.CLOB:
        return "VARBINARY(" + cd.getLength() + ")";
    case Types.VARCHAR:
        return "VARCHAR(" + cd.getLength() + ")";
    case Types.TIME:
        return "TIME";
    case Types.DATE:
        return "DATE";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.CHAR:
        return "CHAR";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.TINYINT:
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT" + (cd.getPrecision() > 0 ? "(" + cd.getPrecision() + ")" : "");
    case Types.DOUBLE:
        return "DOUBLE" + (cd.getPrecision() > 0 ? "(" + cd.getPrecision() + ")" : "");
    case Types.DECIMAL:
        return "DECIMAL" + (cd.getPrecision() > 0
                ? "(" + cd.getPrecision() + (cd.getScale() > 0 ? "," + cd.getScale() : "") + ")"
                : "");
    }

    throw new IllegalArgumentException("Unhandled sql type: " + sqlType);
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Get the Statement column so that the results are mapped correctly.
 * (this has been copied from AbstractDatabaseAction and modified slightly)
 *///  ww  w  . j  av  a 2s.c om
public static Object getColumn(ResultSet set, Configuration column) throws Exception {

    Integer type = (Integer) JDBCTypeConversions.typeConstants.get(column.getAttribute("type"));
    String dbcol = column.getAttribute("name");
    Object value = null;

    switch (type.intValue()) {
    case Types.CLOB:
    case Types.CHAR:
        Clob dbClob = set.getClob(dbcol);
        int length = (int) dbClob.length();
        InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream());
        byte[] buffer = new byte[length];
        asciiStream.read(buffer);
        String str = new String(buffer);
        asciiStream.close();
        value = str;
        break;
    case Types.BIGINT:
        value = set.getBigDecimal(dbcol);
        break;
    case Types.TINYINT:
        value = new Byte(set.getByte(dbcol));
        break;
    case Types.VARCHAR:
        value = set.getString(dbcol);
        break;
    case Types.DATE:
        value = set.getDate(dbcol);
        break;
    case Types.DOUBLE:
        value = new Double(set.getDouble(dbcol));
        break;
    case Types.FLOAT:
        value = new Float(set.getFloat(dbcol));
        break;
    case Types.INTEGER:
        value = new Integer(set.getInt(dbcol));
        break;
    case Types.NUMERIC:
        value = new Long(set.getLong(dbcol));
        break;
    case Types.SMALLINT:
        value = new Short(set.getShort(dbcol));
        break;
    case Types.TIME:
        value = set.getTime(dbcol);
        break;
    case Types.TIMESTAMP:
        value = set.getTimestamp(dbcol);
        break;
    case Types.ARRAY:
        value = set.getArray(dbcol); // new Integer(set.getInt(dbcol));
        break;
    case Types.BIT:
        value = BooleanUtils.toBooleanObject(set.getBoolean(dbcol));
        break;
    case Types.STRUCT:
        value = (Struct) set.getObject(dbcol);
        break;
    case Types.OTHER:
        value = set.getObject(dbcol);
        break;

    default:
        // The blob types have to be requested separately, via a Reader.
        value = "";
        break;
    }

    return value;
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.Type1BlobCollectionConversionHandler.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) {
            //System.out.println("getValidateSource(" + id + ") blob == " + blob + " blob.length == " + blob.length());
            rv = blob.getBytes(1L, (int) blob.length());
        } else {/* w ww. j a v  a 2  s .  c o  m*/
            System.out.println("getValidateSource(" + id + ") blob is 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;
}