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:org.apache.sqoop.hcat.HCatalogExportTest.java

public void testDateTypes() throws Exception {
    final int TOTAL_RECORDS = 1 * 10;
    String table = getTableName().toUpperCase();
    ColumnGenerator[] cols = new ColumnGenerator[] {
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(0), "date", Types.DATE,
                    HCatFieldSchema.Type.STRING, 0, 0, "2013-12-31", new Date(113, 11, 31), KeyType.NOT_A_KEY),
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(1), "date", Types.DATE,
                    HCatFieldSchema.Type.DATE, 0, 0, new Date(113, 11, 31), new Date(113, 11, 31),
                    KeyType.NOT_A_KEY),/*w  w  w . j a  v a 2s.  c  o m*/
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(2), "time", Types.TIME,
                    HCatFieldSchema.Type.STRING, 0, 0, "10:11:12", new Time(10, 11, 12), KeyType.NOT_A_KEY),
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(3), "timestamp", Types.TIMESTAMP,
                    HCatFieldSchema.Type.STRING, 0, 0, "2013-12-31 10:11:12",
                    new Timestamp(113, 11, 31, 10, 11, 12, 0), KeyType.NOT_A_KEY),
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(4), "timestamp", Types.TIMESTAMP,
                    HCatFieldSchema.Type.TIMESTAMP, 0, 0, new Timestamp(113, 11, 31, 10, 11, 12, 0),
                    new Timestamp(113, 11, 31, 10, 11, 12, 0), KeyType.NOT_A_KEY), };
    List<String> addlArgsArray = new ArrayList<String>();
    runHCatExport(addlArgsArray, TOTAL_RECORDS, table, cols);
}

From source file:org.castor.jdo.engine.SQLTypeInfos.java

/**
 * Get value from given ResultSet at given index with given SQL type.
 * /*w w  w . jav  a  2s  .c  o  m*/
 * @param rs The ResultSet to get the value from.
 * @param index The index of the value in the ResultSet.
 * @param sqlType The SQL type of the value.
 * @return The value.
 * @throws SQLException If a database access error occurs.
 */
public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException {
    switch (sqlType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return rs.getString(index);
    case Types.DECIMAL:
    case Types.NUMERIC:
        return rs.getBigDecimal(index);
    case Types.INTEGER:
        int intVal = rs.getInt(index);
        return (rs.wasNull() ? null : new Integer(intVal));
    case Types.TIME:
        return rs.getTime(index, getCalendar());
    case Types.DATE:
        return rs.getDate(index);
    case Types.TIMESTAMP:
        return rs.getTimestamp(index, getCalendar());
    case Types.FLOAT:
    case Types.DOUBLE:
        double doubleVal = rs.getDouble(index);
        return (rs.wasNull() ? null : new Double(doubleVal));
    case Types.REAL:
        float floatVal = rs.getFloat(index);
        return (rs.wasNull() ? null : new Float(floatVal));
    case Types.SMALLINT:
        short shortVal = rs.getShort(index);
        return (rs.wasNull() ? null : new Short(shortVal));
    case Types.TINYINT:
        byte byteVal = rs.getByte(index);
        return (rs.wasNull() ? null : new Byte(byteVal));
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
    case Types.BINARY:
        return rs.getBytes(index);
    case Types.BLOB:
        Blob blob = rs.getBlob(index);
        return (blob == null ? null : blob.getBinaryStream());
    case Types.CLOB:
        return rs.getClob(index);
    case Types.BIGINT:
        long longVal = rs.getLong(index);
        return (rs.wasNull() ? null : new Long(longVal));
    case Types.BIT:
        boolean boolVal = rs.getBoolean(index);
        return (rs.wasNull() ? null : new Boolean(boolVal));
    default:
        Object value = rs.getObject(index);
        return (rs.wasNull() ? null : value);
    }
}

From source file:br.bookmark.db.util.ResultSetUtils.java

/**
 * Map JDBC objects to Java equivalents.
 * Used by getBean() and getBeans().//from   w w w. j  a  v a2  s. c  om
 * <p>
 * Some types not supported.
 * Many not work with all drivers.
 * <p>
 * Makes binary conversions of BIGINT, DATE, DECIMAL, DOUBLE, FLOAT, INTEGER,
 * REAL, SMALLINT, TIME, TIMESTAMP, TINYINT.
 * Makes Sting conversions of CHAR, CLOB, VARCHAR, LONGVARCHAR, BLOB, LONGVARBINARY,
 * VARBINARY.
 * <p>
 * DECIMAL, INTEGER, SMALLINT, TIMESTAMP, CHAR, VARCHAR tested with MySQL and Poolman.
 * Others not guaranteed.
 * @param classeDestino 
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 */
private static void putEntry(Map properties, ResultSetMetaData metaData, ResultSet resultSet, int i,
        Class classeDestino) throws Exception {

    /*
    In a perfect universe, this would be enough
    properties.put(
        metaData.getColumnName(i),
        resultSet.getObject(i));
    But only String, Timestamp, and Integer seem to get through that way.
    */

    String columnName = metaData.getColumnName(i);

    // Testa se  uma FK
    /*Field[] fields = classeDestino.getDeclaredFields();
    for (int j = 0; j < fields.length; j++) {
    if (fields[j].getAnnotation(DBFK.class) != null) {
        properties.put(columnName, resultSet.getString(i));
    }
    }*/
    //System.out.println(i+"-"+metaData.getColumnType(i));
    switch (metaData.getColumnType(i)) {

    // http://java.sun.com/j2se/1.3.0/docs/api/java/sql/Types.html

    case Types.BIGINT:
        properties.put(columnName, new Long(resultSet.getLong(i)));
        break;

    case Types.DATE:
        properties.put(columnName, resultSet.getDate(i));
        break;

    case Types.DECIMAL:
    case Types.DOUBLE:
        properties.put(columnName, new Double(resultSet.getDouble(i)));
        break;

    case Types.FLOAT:
        properties.put(columnName, new Float(resultSet.getFloat(i)));
        break;

    case Types.INTEGER:
        int valor = 0;
        try { // Se o campo esta vazio d erro
            valor = resultSet.getInt(i);
        } catch (SQLException e) {
        }
        properties.put(columnName, new Integer(valor));
        break;

    case Types.REAL:
        properties.put(columnName, new Double(resultSet.getString(i)));
        break;

    case Types.SMALLINT:
        properties.put(columnName, new Short(resultSet.getShort(i)));
        break;

    case Types.TIME:
        properties.put(columnName, resultSet.getTime(i));
        break;

    case Types.TIMESTAMP:
        properties.put(columnName, resultSet.getTimestamp(i));
        break;

    // :FIXME: Throws java.lang.ClassCastException: java.lang.Integer
    // :FIXME: with Poolman and MySQL unless use getString.
    case Types.TINYINT:
        properties.put(columnName, new Byte(resultSet.getString(i)));
        break;

    case Types.CHAR:
    case Types.CLOB:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        // :FIXME: Handle binaries differently?
    case Types.BLOB:
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
        properties.put(columnName, resultSet.getString(i));
        break;

    /*
        :FIXME: Add handlers for
        ARRAY
        BINARY
        BIT
        DISTINCT
        JAVA_OBJECT
        NULL
        NUMERIC
        OTHER
        REF
        STRUCT
    */

    // Otherwise, pass as *String property to be converted
    default:
        properties.put(columnName + "String", resultSet.getString(i));
        break;
    } // end switch

}

From source file:org.apache.sqoop.tool.ImportTool.java

/**
 * Determine if a column is date/time.// ww w .j a  v a  2  s  .c  om
 * @return true if column type is TIMESTAMP, DATE, or TIME.
 */
private boolean isDateTimeColumn(int columnType) {
    return (columnType == Types.TIMESTAMP) || (columnType == Types.DATE) || (columnType == Types.TIME);
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.BaseTableJdbcSourceIT.java

protected static void setParamsToPreparedStatement(PreparedStatement ps, int paramIdx, int sqlType,
        Object value) throws SQLException {
    switch (sqlType) {
    case Types.DATE:
        ps.setDate(paramIdx, new java.sql.Date(((Date) value).getTime()));
        break;/*  ww  w  .j  av  a  2  s . c o m*/
    case Types.TIME:
        ps.setTime(paramIdx, new java.sql.Time(((Date) value).getTime()));
        break;
    case Types.TIMESTAMP:
        ps.setTimestamp(paramIdx, new java.sql.Timestamp(((Date) value).getTime()));
        break;
    default:
        ps.setObject(paramIdx, value);
    }
}

From source file:org.akaza.openclinica.dao.submit.EventCRFDAO.java

public EntityBean create(EntityBean eb) {
    EventCRFBean ecb = (EventCRFBean) eb;
    HashMap variables = new HashMap();
    HashMap nullVars = new HashMap();
    variables.put(new Integer(1), new Integer(ecb.getStudyEventId()));
    variables.put(new Integer(2), new Integer(ecb.getCRFVersionId()));

    Date interviewed = ecb.getDateInterviewed();
    if (interviewed != null) {
        variables.put(new Integer(3), ecb.getDateInterviewed());
    } else {/*from w  ww. j a va 2 s.  c om*/
        variables.put(new Integer(3), null);
        nullVars.put(new Integer(3), new Integer(Types.DATE));
    }
    logger.debug("created: ecb.getInterviewerName()" + ecb.getInterviewerName());
    variables.put(new Integer(4), ecb.getInterviewerName());

    variables.put(new Integer(5), new Integer(ecb.getCompletionStatusId()));
    variables.put(new Integer(6), new Integer(ecb.getStatus().getId()));
    variables.put(new Integer(7), ecb.getAnnotations());
    variables.put(new Integer(8), new Integer(ecb.getOwnerId()));
    variables.put(new Integer(9), new Integer(ecb.getStudySubjectId()));
    variables.put(new Integer(10), ecb.getValidateString());
    variables.put(new Integer(11), ecb.getValidatorAnnotations());

    executeWithPK(digester.getQuery("create"), variables, nullVars);
    if (isQuerySuccessful()) {
        ecb.setId(getLatestPK());
    }

    return ecb;
}

From source file:architecture.user.dao.impl.ExternalJdbcUserDao.java

/**
 *  ? ?./*from   w ww .  j a v  a2s.c  o  m*/
 * 
 * @param u
 */
public User create(User u) {
    UserTemplate user = new UserTemplate(u);
    if (user.getEmail() == null)
        throw new IllegalArgumentException(
                "User has no email address specified.  An email address is required to create a new user.");

    long userId = getNextId(sequencerName);

    user.setUserId(userId);
    if ("".equals(user.getName()))
        user.setName(null);
    user.setEmail(user.getEmail().toLowerCase());
    if (user.getStatus() == null)
        user.setStatus(User.Status.registered);

    boolean useLastNameFirstName = user.getFirstName() != null && user.getLastName() != null;

    try {

        Date now = new Date();

        getExtendedJdbcTemplate().update(getSql("CREATE_USER"),
                new Object[] { userId, user.getUsername(), user.getPasswordHash(),
                        useLastNameFirstName ? null : user.getName(), user.isNameVisible() ? 1 : 0,
                        user.getEmail(), user.isEmailVisible() ? 1 : 0,
                        user.getLastLoggedIn() != null ? user.getLastLoggedIn() : now,

                        user.getLastProfileUpdate() != null ? user.getLastProfileUpdate() : now,
                        user.isEnabled() ? 1 : 0, 1, user.isExternal() ? 1 : 0, user.isFederated() ? 1 : 0,
                        user.getStatus().getId(), user.getCreationDate() != null ? user.getCreationDate() : now,
                        user.getModifiedDate() != null ? user.getModifiedDate() : now },
                new int[] { Types.NUMERIC, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.NUMERIC,
                        Types.VARCHAR, Types.NUMERIC, Types.DATE,

                        Types.DATE, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC,
                        Types.DATE, Types.DATE });

        setUserProfile(user.getUserId(), user.getProfile());
        setUserProperties(user.getUserId(), user.getProperties());

    } catch (DataAccessException e) {
        String message = "Failed to create new user.";
        log.fatal(message, e);
        throw e;
    }
    return user;
}

From source file:oscar.form.FrmONAREnhancedRecord.java

int addRecord(Properties props, String table, List<String> namesA, Integer id) throws SQLException {
    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO " + table + " (");
    for (String name : namesA) {
        sb.append(name.split("\\|")[0] + ",");
    }/*w ww .  j ava2 s  .  c  o m*/
    sb.deleteCharAt(sb.length() - 1);

    sb.append(") VALUES (");

    for (String name : namesA) {
        sb.append("?,");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(");");

    PreparedStatement preparedStmt = null;
    try {
        preparedStmt = DbConnectionFilter.getThreadLocalDbConnection().prepareStatement(sb.toString(),
                Statement.RETURN_GENERATED_KEYS);

        for (int x = 0; x < namesA.size(); x++) {
            String t = namesA.get(x);
            String theName = t.split("\\|")[0];
            String type = t.split("\\|")[1];

            if (theName.equals("ID")) {
                if (id == null) {
                    preparedStmt.setNull(x + 1, Types.INTEGER);
                } else {
                    preparedStmt.setInt(x + 1, id.intValue());
                }
                continue;
            }

            if (type.equals("VARCHAR") || type.equals("CHAR")) {
                String value = props.getProperty(theName);
                if (value == null) {
                    preparedStmt.setNull(x + 1, getType(type));
                } else {
                    preparedStmt.setString(x + 1, value);
                }
            } else if (type.equals("INT") || type.equals("TINYINT")) {
                String value = props.getProperty(theName);
                if (value != null && value.isEmpty()) {
                    MiscUtils.getLogger().info("empty value for " + theName);
                }
                if (value == null || value.isEmpty()) {
                    value = "0";
                } else if (value.equalsIgnoreCase("on") || value.equalsIgnoreCase("checked='checked'")) {
                    value = "1";
                }
                preparedStmt.setInt(x + 1, Integer.parseInt(value));
            } else if (type.equals("DATE")) {
                String value = props.getProperty(theName);
                Date d = null;

                if (theName.equalsIgnoreCase("formEdited")) {
                    d = new Date();
                } else {
                    if ((value == null) || (value.indexOf('/') != -1))
                        d = UtilDateUtilities.StringToDate(value, dateFormat);
                    else
                        d = UtilDateUtilities.StringToDate(value, _newDateFormat);
                }
                if (d == null)
                    preparedStmt.setNull(x + 1, Types.DATE);
                else
                    preparedStmt.setDate(x + 1, new java.sql.Date(d.getTime()));

            } else if (type.equals("TIMESTAMP")) {
                Date d;
                if (theName.equalsIgnoreCase("formEdited")) {
                    d = new Date();
                } else {
                    d = UtilDateUtilities.StringToDate(props.getProperty(theName), "yyyyMMddHHmmss");
                }
                if (d == null)
                    preparedStmt.setNull(x + 1, Types.TIMESTAMP);
                else
                    preparedStmt.setTimestamp(x + 1, new java.sql.Timestamp(d.getTime()));

            } else {
                MiscUtils.getLogger().error("missing type handler for this column " + theName, new Exception());
            }

        }

        preparedStmt.executeUpdate();

        if (id == null) {
            ResultSet rs = null;
            try {
                rs = preparedStmt.getGeneratedKeys();

                if (rs.next()) {
                    id = rs.getInt(1);
                }
            } finally {
                if (rs != null)
                    rs.close();
            }

        }
    } finally {
        if (preparedStmt != null) {
            preparedStmt.close();
        }
    }

    return id;
}

From source file:org.jfree.data.jdbc.JDBCCategoryDataset.java

/**
 * Populates the dataset by executing the supplied query against the
 * existing database connection.  If no connection exists then no action
 * is taken./*from   w ww . jav  a 2s .c  o  m*/
 * <p>
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param con  the connection.
 * @param query  the query.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();

        if (columnCount < 2) {
            throw new SQLException("JDBCCategoryDataset.executeQuery() : insufficient columns "
                    + "returned from the database.");
        }

        // Remove any previous old data
        int i = getRowCount();
        while (--i >= 0) {
            removeRow(i);
        }

        while (resultSet.next()) {
            // first column contains the row key...
            Comparable rowKey = resultSet.getString(1);
            for (int column = 2; column <= columnCount; column++) {

                Comparable columnKey = metaData.getColumnName(column);
                int columnType = metaData.getColumnType(column);

                switch (columnType) {
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.INTEGER:
                case Types.BIGINT:
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.DECIMAL:
                case Types.NUMERIC:
                case Types.REAL: {
                    Number value = (Number) resultSet.getObject(column);
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP: {
                    Date date = (Date) resultSet.getObject(column);
                    Number value = new Long(date.getTime());
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGVARCHAR: {
                    String string = (String) resultSet.getObject(column);
                    try {
                        Number value = Double.valueOf(string);
                        if (this.transpose) {
                            setValue(value, columnKey, rowKey);
                        } else {
                            setValue(value, rowKey, columnKey);
                        }
                    } catch (NumberFormatException e) {
                        // suppress (value defaults to null)
                    }
                    break;
                }
                default:
                    // not a value, can't use it (defaults to null)
                    break;
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // report this?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // report this?
            }
        }
    }
}

From source file:org.pentaho.metadata.util.SQLModelGenerator.java

private static DataType converDataType(int type) {
    switch (type) {
    case Types.FLOAT:
    case Types.BIT:
    case Types.DOUBLE:
    case Types.SMALLINT:
    case Types.REAL:
    case Types.DECIMAL:
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.NUMERIC:
        return DataType.NUMERIC;

    case Types.BINARY:
    case Types.CLOB:
    case Types.BLOB:
        return DataType.BINARY;

    case Types.BOOLEAN:
        return DataType.BOOLEAN;

    case Types.DATE:
        return DataType.DATE;

    case Types.TIMESTAMP:
        return DataType.DATE;

    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        return DataType.STRING;

    default://from   w  w w.j  av  a2  s  . c  o  m
        return DataType.UNKNOWN;
    }
}