Example usage for java.sql Types DATE

List of usage examples for java.sql Types DATE

Introduction

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

Prototype

int DATE

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

Click Source Link

Document

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

Usage

From source file:oscar.util.SqlUtils.java

/**
 * this utility-method assigns a particular value to a place holder of a PreparedStatement. it tries to find the correct setXxx() value, accoring to the field-type information
 * represented by "fieldType". quality: this method is bloody alpha (as you migth see :=)
 *//*from w  w w . ja  v a 2  s.  c  o m*/
public static void fillPreparedStatement(PreparedStatement ps, int col, Object val, int fieldType)
        throws SQLException {
    try {
        logger.info("fillPreparedStatement( ps, " + col + ", " + val + ", " + fieldType + ")...");
        Object value = null;
        // Check for hard-coded NULL
        if (!("$null$".equals(val))) {
            value = val;
        }
        if (value != null) {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setInt(col, Integer.parseInt((String) value));
                break;
            case FieldTypes.NUMERIC:
                ps.setBigDecimal(col, createAppropriateNumeric(value));
                break;
            case FieldTypes.CHAR:
                ps.setString(col, (String) value);
                break;
            case FieldTypes.DATE:
                ps.setDate(col, createAppropriateDate(value));
                break; // #checkme
            case FieldTypes.TIMESTAMP:
                ps.setTimestamp(col, java.sql.Timestamp.valueOf((String) value));
                break;
            case FieldTypes.DOUBLE:
                ps.setDouble(col, Double.valueOf((String) value).doubleValue());
                break;
            case FieldTypes.FLOAT:
                ps.setFloat(col, Float.valueOf((String) value).floatValue());
                break;
            case FieldTypes.LONG:
                ps.setLong(col, Long.parseLong(String.valueOf(value)));
                break;
            case FieldTypes.BLOB:
                FileHolder fileHolder = (FileHolder) value;
                try {
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(byteOut);
                    out.writeObject(fileHolder);
                    out.flush();
                    byte[] buf = byteOut.toByteArray();
                    byteOut.close();
                    out.close();
                    ByteArrayInputStream bytein = new ByteArrayInputStream(buf);
                    int byteLength = buf.length;
                    ps.setBinaryStream(col, bytein, byteLength);
                    // store fileHolder as a whole (this way we don't lose file meta-info!)
                } catch (IOException ioe) {
                    MiscUtils.getLogger().error("Error", ioe);
                    logger.info(ioe.toString());
                    throw new SQLException("error storing BLOB in database - " + ioe.toString(), null, 2);
                }
                break;
            case FieldTypes.DISKBLOB:
                ps.setString(col, (String) value);
                break;
            default:
                ps.setObject(col, value); // #checkme
            }
        } else {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setNull(col, java.sql.Types.INTEGER);
                break;
            case FieldTypes.NUMERIC:
                ps.setNull(col, java.sql.Types.NUMERIC);
                break;
            case FieldTypes.CHAR:
                ps.setNull(col, java.sql.Types.CHAR);
                break;
            case FieldTypes.DATE:
                ps.setNull(col, java.sql.Types.DATE);
                break;
            case FieldTypes.TIMESTAMP:
                ps.setNull(col, java.sql.Types.TIMESTAMP);
                break;
            case FieldTypes.DOUBLE:
                ps.setNull(col, java.sql.Types.DOUBLE);
                break;
            case FieldTypes.FLOAT:
                ps.setNull(col, java.sql.Types.FLOAT);
                break;
            case FieldTypes.BLOB:
                ps.setNull(col, java.sql.Types.BLOB);
            case FieldTypes.DISKBLOB:
                ps.setNull(col, java.sql.Types.CHAR);
            default:
                ps.setNull(col, java.sql.Types.OTHER);
            }
        }
    } catch (Exception e) {
        throw new SQLException("Field type seems to be incorrect - " + e.toString(), null, 1);
    }
}

From source file:org.apache.phoenix.pig.util.TypeUtil.java

/**
 * This method encodes a value with Phoenix data type. It begins with checking whether an object is BINARY and makes
 * a call to {@link #castBytes(Object, PDataType)} to convert bytes to targetPhoenixType. It returns a {@link RuntimeException}
 * when object can not be coerced./* w ww . ja  v a 2s .  c om*/
 * 
 * @param o
 * @param targetPhoenixType
 * @return Object
 */
public static Object castPigTypeToPhoenix(Object o, byte objectType, PDataType targetPhoenixType) {
    PDataType inferredPType = getType(o, objectType);

    if (inferredPType == null) {
        return null;
    }

    if (inferredPType == PVarbinary.INSTANCE) {
        try {
            o = castBytes(o, targetPhoenixType);
            if (targetPhoenixType != PVarbinary.INSTANCE && targetPhoenixType != PBinary.INSTANCE) {
                inferredPType = getType(o, DataType.findType(o));
            }
        } catch (IOException e) {
            throw new RuntimeException("Error while casting bytes for object " + o);
        }
    }
    if (inferredPType == PDate.INSTANCE) {
        int inferredSqlType = targetPhoenixType.getSqlType();

        if (inferredSqlType == Types.DATE) {
            return new Date(((DateTime) o).getMillis());
        }
        if (inferredSqlType == Types.TIME) {
            return new Time(((DateTime) o).getMillis());
        }
        if (inferredSqlType == Types.TIMESTAMP) {
            return new Timestamp(((DateTime) o).getMillis());
        }
    }

    if (targetPhoenixType == inferredPType || inferredPType.isCoercibleTo(targetPhoenixType)) {
        return inferredPType.toObject(o, targetPhoenixType);
    }

    throw new RuntimeException(
            o.getClass().getName() + " cannot be coerced to " + targetPhoenixType.toString());
}

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

/**
 * Return the java type for the given SQL type from {@link Types}.
 *///  ww  w .j a  v  a2  s.co 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:org.executequery.gui.resultset.ResultSetTableModel.java

public void createTable(ResultSet resultSet) {

    if (!isOpenAndValid(resultSet)) {

        clearData();//from  w  w w  . j  a v a2 s .c om
        return;
    }

    try {

        resetMetaData();
        ResultSetMetaData rsmd = resultSet.getMetaData();

        columnHeaders.clear();
        visibleColumnHeaders.clear();
        tableData.clear();

        int zeroBaseIndex = 0;
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {

            zeroBaseIndex = i - 1;

            columnHeaders.add(new ResultSetColumnHeader(zeroBaseIndex, rsmd.getColumnLabel(i),
                    rsmd.getColumnName(i), rsmd.getColumnType(i), rsmd.getColumnTypeName(i)));
        }

        int recordCount = 0;
        interrupted = false;

        if (holdMetaData) {

            setMetaDataVectors(rsmd);
        }

        List<RecordDataItem> rowData;
        long time = System.currentTimeMillis();
        while (resultSet.next()) {

            if (interrupted || Thread.interrupted()) {

                throw new InterruptedException();
            }

            recordCount++;
            rowData = new ArrayList<RecordDataItem>(count);

            for (int i = 1; i <= count; i++) {

                zeroBaseIndex = i - 1;

                ResultSetColumnHeader header = columnHeaders.get(zeroBaseIndex);
                RecordDataItem value = recordDataItemFactory.create(header);

                try {

                    int dataType = header.getDataType();
                    switch (dataType) {

                    // some drivers (informix for example)
                    // was noticed to return the hashcode from
                    // getObject for -1 data types (eg. longvarchar).
                    // force string for these - others stick with
                    // getObject() for default value formatting

                    case Types.CHAR:
                    case Types.VARCHAR:
                        value.setValue(resultSet.getString(i));
                        break;
                    case Types.DATE:
                        value.setValue(resultSet.getDate(i));
                        break;
                    case Types.TIME:
                        value.setValue(resultSet.getTime(i));
                        break;
                    case Types.TIMESTAMP:
                        value.setValue(resultSet.getTimestamp(i));
                        break;
                    case Types.LONGVARCHAR:
                    case Types.CLOB:
                        value.setValue(resultSet.getClob(i));
                        break;
                    case Types.LONGVARBINARY:
                    case Types.VARBINARY:
                    case Types.BINARY:
                        value.setValue(resultSet.getBytes(i));
                        break;
                    case Types.BLOB:
                        value.setValue(resultSet.getBlob(i));
                        break;
                    case Types.BIT:
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                    case Types.FLOAT:
                    case Types.REAL:
                    case Types.DOUBLE:
                    case Types.NUMERIC:
                    case Types.DECIMAL:
                    case Types.NULL:
                    case Types.OTHER:
                    case Types.JAVA_OBJECT:
                    case Types.DISTINCT:
                    case Types.STRUCT:
                    case Types.ARRAY:
                    case Types.REF:
                    case Types.DATALINK:
                    case Types.BOOLEAN:
                    case Types.ROWID:
                    case Types.NCHAR:
                    case Types.NVARCHAR:
                    case Types.LONGNVARCHAR:
                    case Types.NCLOB:
                    case Types.SQLXML:

                        // use getObject for all other known types

                        value.setValue(resultSet.getObject(i));
                        break;

                    default:

                        // otherwise try as string

                        asStringOrObject(value, resultSet, i);
                        break;
                    }

                } catch (Exception e) {

                    try {

                        // ... and on dump, resort to string
                        value.setValue(resultSet.getString(i));

                    } catch (SQLException sqlException) {

                        // catch-all SQLException - yes, this is hideous

                        // noticed with invalid date formatted values in mysql

                        value.setValue("<Error - " + sqlException.getMessage() + ">");
                    }
                }

                if (resultSet.wasNull()) {

                    value.setNull();
                }

                rowData.add(value);
            }

            tableData.add(rowData);

            if (recordCount == maxRecords) {

                break;
            }

        }

        if (Log.isTraceEnabled()) {

            Log.trace("Finished populating table model - " + recordCount + " rows - [ "
                    + MiscUtils.formatDuration(System.currentTimeMillis() - time) + "]");
        }

        fireTableStructureChanged();

    } catch (SQLException e) {

        System.err.println("SQL error populating table model at: " + e.getMessage());
        Log.debug("Table model error - " + e.getMessage(), e);

    } catch (Exception e) {

        if (e instanceof InterruptedException) {

            Log.debug("ResultSet generation interrupted.", e);

        } else {

            String message = e.getMessage();
            if (StringUtils.isBlank(message)) {

                System.err.println("Exception populating table model.");

            } else {

                System.err.println("Exception populating table model at: " + message);
            }

            Log.debug("Table model error - ", e);
        }

    } finally {

        if (resultSet != null) {

            try {

                resultSet.close();

                Statement statement = resultSet.getStatement();
                if (statement != null) {

                    statement.close();
                }

            } catch (SQLException e) {
            }

        }
    }

}

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)
 *///from w w  w.j  a va 2  s.  c o m
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.syncope.core.util.ImportExport.java

private void setParameters(final String tableName, final Attributes atts, final Query query) {

    Map<String, Integer> colTypes = new HashMap<String, Integer>();

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;/*from   w w w  .j a v  a 2  s .  c om*/
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM " + tableName);
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            colTypes.put(rs.getMetaData().getColumnName(i + 1).toUpperCase(),
                    rs.getMetaData().getColumnType(i + 1));
        }
    } catch (SQLException e) {
        LOG.error("While", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing statement", e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    for (int i = 0; i < atts.getLength(); i++) {
        Integer colType = colTypes.get(atts.getQName(i).toUpperCase());
        if (colType == null) {
            LOG.warn("No column type found for {}", atts.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }

        switch (colType) {
        case Types.NUMERIC:
        case Types.REAL:
        case Types.INTEGER:
        case Types.TINYINT:
            try {
                query.setParameter(i + 1, Integer.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Integer '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DECIMAL:
        case Types.BIGINT:
            try {
                query.setParameter(i + 1, Long.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Long '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DOUBLE:
            try {
                query.setParameter(i + 1, Double.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Double '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.FLOAT:
            try {
                query.setParameter(i + 1, Float.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Float '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            try {
                query.setParameter(i + 1, DateUtils.parseDate(atts.getValue(i), SyncopeConstants.DATE_PATTERNS),
                        TemporalType.TIMESTAMP);
            } catch (ParseException e) {
                LOG.error("Unparsable Date '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            query.setParameter(i + 1, "1".equals(atts.getValue(i)) ? Boolean.TRUE : Boolean.FALSE);
            break;

        default:
            query.setParameter(i + 1, atts.getValue(i));
        }
    }
}

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

protected int getTypeCode(Column column, boolean isDateOverrideToTimestamp) {
    int type = column.getMappedTypeCode();
    if (type == Types.DATE && isDateOverrideToTimestamp) {
        type = Types.TIMESTAMP;/*from w  ww.  jav a2  s.c  om*/
    } else if (type == Types.FLOAT || type == Types.DOUBLE || type == Types.REAL) {
        type = Types.DECIMAL;
    }
    return type;
}

From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.IdeaInstanceDAO.java

private void insertIdeaInstance(IdeaInstance ideainstance, Connection conn) {
    PreparedStatement stat = null;
    try {//from  w  ww . j a v a2  s.c om
        stat = conn.prepareStatement(ADD_IDEAINSTANCE);
        int index = 1;
        stat.setString(index++, ideainstance.getCode());
        if (null != ideainstance.getCreatedat()) {
            Timestamp createdatTimestamp = new Timestamp(ideainstance.getCreatedat().getTime());
            stat.setTimestamp(index++, createdatTimestamp);
        } else {
            stat.setNull(index++, Types.DATE);
        }
        stat.executeUpdate();
    } catch (Throwable t) {
        _logger.error("Error in insert ideainstance", t);
        throw new RuntimeException("Error in insert ideainstance", t);
    } finally {
        this.closeDaoResources(null, stat, null);
    }
}

From source file:org.apache.syncope.core.util.ContentExporter.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;//from  w w  w . j  a v a  2 s. co m

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(is)));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream())));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = DataFormat.format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}

From source file:net.riezebos.thoth.configuration.persistence.dbs.DDLExecuter.java

private void initDialect(DatabaseIdiom idiom) {
    databaseIdiom = idiom;//from ww w .ja v  a  2 s . c  o m
    try {
        addTranslation("bigint", idiom.getTypeName(Types.BIGINT));
        addTranslation("binary", idiom.getTypeName(Types.BINARY));
        addTranslation("bit", idiom.getTypeName(Types.BIT));
        addTranslation("blob", idiom.getTypeName(Types.BLOB));
        addTranslation("boolean", idiom.getTypeName(Types.BOOLEAN));
        addTranslation("char", idiom.getTypeName(Types.CHAR));
        addTranslation("clob", idiom.getTypeName(Types.CLOB));
        addTranslation("date", idiom.getTypeName(Types.DATE));
        addTranslation("decimal", idiom.getTypeName(Types.DECIMAL));
        addTranslation("double", idiom.getTypeName(Types.DOUBLE));
        addTranslation("float", idiom.getTypeName(Types.FLOAT));
        addTranslation("integer", idiom.getTypeName(Types.INTEGER));
        addTranslation("longnvarchar", idiom.getTypeName(Types.LONGNVARCHAR));
        addTranslation("longvarbinary", idiom.getTypeName(Types.LONGVARBINARY));
        addTranslation("longvarchar", idiom.getTypeName(Types.LONGVARCHAR));
        addTranslation("nchar", idiom.getTypeName(Types.NCHAR));
        addTranslation("nclob", idiom.getTypeName(Types.NCLOB));
        addTranslation("numeric", idiom.getTypeName(Types.NUMERIC));
        addTranslation("nvarchar", idiom.getTypeName(Types.NVARCHAR));
        addTranslation("real", idiom.getTypeName(Types.REAL));
        addTranslation("smallint", idiom.getTypeName(Types.SMALLINT));
        addTranslation("time", idiom.getTypeName(Types.TIME));
        addTranslation("timestamp", idiom.getTypeName(Types.TIMESTAMP));
        addTranslation("tinyint", idiom.getTypeName(Types.TINYINT));
        addTranslation("varbinary", idiom.getTypeName(Types.VARBINARY));

        databaseIdiom.initDialect(translations, workarounds);
        // Ignore autogenerated ID's
        addWorkaround("generated always as identity", "");
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}