Example usage for java.sql Types TIMESTAMP

List of usage examples for java.sql Types TIMESTAMP

Introduction

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

Prototype

int TIMESTAMP

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

Click Source Link

Document

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

Usage

From source file:org.easyrec.mahout.store.impl.MahoutDataModelMappingDAOMysqlImpl.java

@Override
public int getNumUsersWithPreferenceFor(int tenantId, Date cutoffDate, long itemID1, long itemID2,
        int actionTypeId) {
    Object[] args = new Object[] { tenantId, cutoffDate, itemID1, itemID2, actionTypeId };
    int[] argTypes = new int[] { Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER, Types.INTEGER };

    return getJdbcTemplate().queryForInt(getNumUsersWithPreferenceForTwoQuery, args, argTypes);
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

@Test
public void testObjectTimestamp() throws Exception {
    Statement stmt = con.createStatement();
    java.util.Date now = new java.util.Date();

    // Create the target Column family
    //String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";        
    String createCF = "CREATE COLUMNFAMILY t74 (id BIGINT PRIMARY KEY, col1 TIMESTAMP)";

    stmt.execute(createCF);/*from   w  w  w.ja v a  2 s.  co  m*/
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));

    Statement statement = con.createStatement();

    String insert = "INSERT INTO t74 (id, col1) VALUES (?, ?);";

    PreparedStatement pstatement = con.prepareStatement(insert);
    pstatement.setLong(1, 1L);
    pstatement.setObject(2, new Timestamp(now.getTime()), Types.TIMESTAMP);
    pstatement.execute();

    ResultSet result = statement.executeQuery("SELECT * FROM t74;");

    assertTrue(result.next());
    assertEquals(1L, result.getLong(1));

    // try reading Timestamp directly
    Timestamp stamp = result.getTimestamp(2);
    assertEquals(now, stamp);

    // try reading Timestamp as an object
    stamp = result.getObject(2, Timestamp.class);
    assertEquals(now, stamp);

    System.out.println(resultToDisplay(result, 74, "current date"));

}

From source file:org.jumpmind.symmetric.service.impl.FileSyncService.java

public void save(ISqlTransaction sqlTransaction, FileSnapshot snapshot) {
    snapshot.setLastUpdateTime(new Date());
    if (0 == sqlTransaction.prepareAndExecute(getSql("updateFileSnapshotSql"),
            new Object[] { snapshot.getLastEventType().getCode(), snapshot.getCrc32Checksum(),
                    snapshot.getFileSize(), snapshot.getFileModifiedTime(), snapshot.getLastUpdateTime(),
                    snapshot.getLastUpdateBy(), snapshot.getChannelId(), snapshot.getReloadChannelId(),
                    snapshot.getTriggerId(), snapshot.getRouterId(), snapshot.getRelativeDir(),
                    snapshot.getFileName() },
            new int[] { Types.VARCHAR, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC, Types.TIMESTAMP,
                    Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                    Types.VARCHAR })) {
        snapshot.setCreateTime(snapshot.getLastUpdateTime());
        sqlTransaction.prepareAndExecute(getSql("insertFileSnapshotSql"),
                new Object[] { snapshot.getLastEventType().getCode(), snapshot.getCrc32Checksum(),
                        snapshot.getFileSize(), snapshot.getFileModifiedTime(), snapshot.getCreateTime(),
                        snapshot.getLastUpdateTime(), snapshot.getLastUpdateBy(), snapshot.getChannelId(),
                        snapshot.getReloadChannelId(), snapshot.getTriggerId(), snapshot.getRouterId(),
                        snapshot.getRelativeDir(), snapshot.getFileName() },
                new int[] { Types.VARCHAR, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC, Types.TIMESTAMP,
                        Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                        Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
    }/*  w w  w  .  j  av a 2  s. c o m*/
    // now that we have captured an update, delete the row for cleanup
    if (snapshot.getLastEventType() == LastEventType.DELETE) {
        sqlTransaction.prepareAndExecute(getSql("deleteFileSnapshotSql"),
                new Object[] { snapshot.getTriggerId(), snapshot.getRouterId(), snapshot.getRelativeDir(),
                        snapshot.getFileName() },
                new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
    }

}

From source file:org.easyrec.mahout.store.impl.MahoutDataModelMappingDAOMysqlImpl.java

@Override
public boolean hasPreferenceValues(int tenantId, Date cutoffDate, int actionTypeId) {
    Object[] args = new Object[] { tenantId, cutoffDate, actionTypeId };
    int[] argTypes = new int[] { Types.INTEGER, Types.TIMESTAMP, Types.INTEGER };

    return (getJdbcTemplate().queryForInt(hasPreferenceValuesQuery, args, argTypes) == 1);
}

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

public String buildDynamicSql(BinaryEncoding encoding, Row row, boolean useVariableDates,
        boolean useJdbcTimestampFormat, Column[] columns) {
    final String QUESTION_MARK = "<!QUESTION_MARK!>";
    String newSql = sql;//from  w  w w  . j av  a  2s. co  m
    String quote = databaseInfo.getValueQuoteToken();
    String binaryQuoteStart = databaseInfo.getBinaryQuoteStart();
    String binaryQuoteEnd = databaseInfo.getBinaryQuoteEnd();
    String regex = "\\?";

    List<Column> columnsToProcess = new ArrayList<Column>();
    columnsToProcess.addAll(Arrays.asList(columns));

    for (int i = 0; i < columnsToProcess.size(); i++) {
        Column column = columnsToProcess.get(i);
        String name = column.getName();
        int type = column.getMappedTypeCode();

        if (row.get(name) != null) {
            if (column.isOfTextType()) {
                try {
                    String value = row.getString(name);
                    value = value.replace("\\", "\\\\");
                    value = value.replace("$", "\\$");
                    value = value.replace("'", "''");
                    value = value.replace("?", QUESTION_MARK);
                    newSql = newSql.replaceFirst(regex, quote + value + quote);
                } catch (RuntimeException ex) {
                    log.error("Failed to replace ? in {" + sql + "} with " + name + "=" + row.getString(name));
                    throw ex;
                }
            } else if (column.isTimestampWithTimezone()) {
                newSql = newSql.replaceFirst(regex, quote + row.getString(name) + quote);
            } else if (type == Types.DATE || type == Types.TIMESTAMP || type == Types.TIME) {
                Date date = row.getDateTime(name);
                if (useVariableDates) {
                    long diff = date.getTime() - System.currentTimeMillis();
                    newSql = newSql.replaceFirst(regex, "${curdate" + diff + "}");
                } else if (type == Types.TIME) {
                    newSql = newSql.replaceFirst(regex,
                            (useJdbcTimestampFormat ? "{ts " : "") + quote
                                    + FormatUtils.TIME_FORMATTER.format(date) + quote
                                    + (useJdbcTimestampFormat ? "}" : ""));
                } else {
                    newSql = newSql.replaceFirst(regex,
                            (useJdbcTimestampFormat ? "{ts " : "") + quote
                                    + FormatUtils.TIMESTAMP_FORMATTER.format(date) + quote
                                    + (useJdbcTimestampFormat ? "}" : ""));
                }
            } else if (column.isOfBinaryType()) {
                byte[] bytes = row.getBytes(name);
                if (encoding == BinaryEncoding.NONE) {
                    newSql = newSql.replaceFirst(regex, quote + row.getString(name));
                } else if (encoding == BinaryEncoding.BASE64) {
                    newSql = newSql.replaceFirst(regex, quote + new String(Base64.encodeBase64(bytes)) + quote);
                } else if (encoding == BinaryEncoding.HEX) {
                    newSql = newSql.replaceFirst(regex,
                            binaryQuoteStart + new String(Hex.encodeHex(bytes)) + binaryQuoteEnd);
                }
            } else {
                newSql = newSql.replaceFirst(regex, row.getString(name));
            }
        } else {
            newSql = newSql.replaceFirst(regex, "null");
        }
    }

    newSql = newSql.replace(QUESTION_MARK, "?");
    return newSql + databaseInfo.getSqlCommandDelimiter();
}

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

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

    String res = null;//from w w  w  .ja v a2  s.c o 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 = DATE_FORMAT.get().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:org.apache.openjpa.persistence.jdbc.AnnotationPersistenceMappingSerializer.java

/**
 * Return field's temporal type.//from  ww w.  j a  v  a2 s .  com
 */
private TemporalType getTemporal(FieldMapping field) {
    if (field.getDeclaredTypeCode() != JavaTypes.DATE && field.getDeclaredTypeCode() != JavaTypes.CALENDAR)
        return null;

    DBDictionary dict = ((JDBCConfiguration) getConfiguration()).getDBDictionaryInstance();
    int def = dict.getJDBCType(field.getTypeCode(), false);
    for (Column col : (List<Column>) field.getValueInfo().getColumns()) {
        if (col.getType() == def)
            continue;
        switch (col.getType()) {
        case Types.DATE:
            return TemporalType.DATE;
        case Types.TIME:
            return TemporalType.TIME;
        case Types.TIMESTAMP:
            return TemporalType.TIMESTAMP;
        }
    }
    return null;
}

From source file:org.easyrec.store.dao.core.impl.ItemAssocDAOMysqlImpl.java

/**
 * updates an item association entry in the database, uses the unique key to retrieve the entry
 * only changes columns:<br/>/* w w w.j  a  v a2  s  .  c  o m*/
 * - assocValue<br/>
 * - viewType<br/>
 * - changeDate<br/>
 * <br/>
 * unique key: (tenantId, itemFromId, itemToId, itemFromTypeId, itemToTypeId, assocTypeId, sourceTypeId, sourceInfo)
 */
@Override
public int updateItemAssocUsingUniqueKey(ItemAssocVO<Integer, Integer> itemAssoc) {
    // validate input parameters
    if (itemAssoc == null) {
        throw new IllegalArgumentException("missing 'itemAssoc'");
    }

    validateUniqueKey(itemAssoc);
    validateAssocValue(itemAssoc);
    validateViewType(itemAssoc);

    if (logger.isDebugEnabled()) {
        logger.debug("updating 'itemAssoc' by unique key: " + itemAssoc);
    }

    StringBuilder sqlString;

    sqlString = new StringBuilder("UPDATE ");
    sqlString.append(DEFAULT_TABLE_NAME);
    sqlString.append(" SET ");
    sqlString.append(DEFAULT_ASSOC_VALUE_COLUMN_NAME);
    sqlString.append("=?, ");
    sqlString.append(DEFAULT_VIEW_TYPE_COLUMN_NAME);
    sqlString.append("=?, ");
    if (itemAssoc.isActive() != null) {
        sqlString.append(DEFAULT_ACTIVE_COLUMN_NAME);
        sqlString.append("=?, ");
    }
    sqlString.append(DEFAULT_CHANGE_DATE_COLUMN_NAME);
    if (itemAssoc.getChangeDate() == null) {
        itemAssoc.setChangeDate(new Date(System.currentTimeMillis()));
    }
    sqlString.append("=? WHERE ");
    sqlString.append(DEFAULT_ITEM_FROM_COLUMN_NAME);
    sqlString.append("=? AND ");
    sqlString.append(DEFAULT_ITEM_TO_COLUMN_NAME);
    sqlString.append("=? AND ");
    sqlString.append(DEFAULT_ITEM_FROM_TYPE_COLUMN_NAME);
    sqlString.append("=? AND ");
    sqlString.append(DEFAULT_ITEM_TO_TYPE_COLUMN_NAME);
    sqlString.append("=? AND ");
    sqlString.append(DEFAULT_ASSOC_TYPE_COLUMN_NAME);
    sqlString.append("=? AND ");
    sqlString.append(DEFAULT_SOURCE_TYPE_COLUMN_NAME);
    sqlString.append("=? AND ");
    sqlString.append(DEFAULT_TENANT_COLUMN_NAME);
    sqlString.append("=?");

    Object[] args;
    int[] argTypes;
    if (itemAssoc.isActive() != null) {
        args = new Object[] { itemAssoc.getAssocValue(), itemAssoc.getViewType(), itemAssoc.isActive(),
                itemAssoc.getChangeDate(), itemAssoc.getItemFrom().getItem(), itemAssoc.getItemTo().getItem(),
                itemAssoc.getItemFrom().getType(), itemAssoc.getItemTo().getType(), itemAssoc.getAssocType(),
                itemAssoc.getSourceType(), itemAssoc.getTenant() };
        argTypes = new int[] { Types.DOUBLE, Types.INTEGER, Types.BOOLEAN, Types.TIMESTAMP, Types.INTEGER,
                Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER };
    } else {
        args = new Object[] { itemAssoc.getAssocValue(), itemAssoc.getViewType(), itemAssoc.getChangeDate(),
                itemAssoc.getItemFrom().getItem(), itemAssoc.getItemTo().getItem(),
                itemAssoc.getItemFrom().getType(), itemAssoc.getItemTo().getType(), itemAssoc.getAssocType(),
                itemAssoc.getSourceType(), itemAssoc.getTenant() };
        argTypes = new int[] { Types.DOUBLE, Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER,
                Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER };
    }
    return getJdbcTemplate().update(sqlString.toString(), args, argTypes);
}

From source file:org.apache.sqoop.hcat.HCatalogImportTest.java

public void testDateTypesToBigInt() throws Exception {
    final int TOTAL_RECORDS = 1 * 10;
    long offset = TimeZone.getDefault().getRawOffset();
    String table = getTableName().toUpperCase();
    ColumnGenerator[] cols = new ColumnGenerator[] {
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(0), "date", Types.DATE,
                    HCatFieldSchema.Type.BIGINT, 0, 0, 0 - offset, new Date(70, 0, 1), KeyType.NOT_A_KEY),
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(1), "time", Types.TIME,
                    HCatFieldSchema.Type.BIGINT, 0, 0, 36672000L - offset, new Time(10, 11, 12),
                    KeyType.NOT_A_KEY),// w  ww  . ja  v  a2  s . c  o  m
            HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(2), "timestamp", Types.TIMESTAMP,
                    HCatFieldSchema.Type.BIGINT, 0, 0, 36672000L - offset,
                    new Timestamp(70, 0, 1, 10, 11, 12, 0), KeyType.NOT_A_KEY), };
    List<String> addlArgsArray = new ArrayList<String>();
    addlArgsArray.add("--map-column-hive");
    addlArgsArray.add("COL0=bigint,COL1=bigint,COL2=bigint");
    setExtraArgs(addlArgsArray);
    runHCatImport(addlArgsArray, TOTAL_RECORDS, table, cols, null);
}

From source file:org.apache.empire.db.codegen.CodeGenParser.java

/**
 * converts a SQL DataType to a EmpireDataType
 */// ww  w.j  a v a2  s  . c om
private DataType getEmpireDataType(int sqlType) {
    DataType empireType = DataType.UNKNOWN;
    switch (sqlType) {
    case Types.INTEGER:
    case Types.SMALLINT:
    case Types.TINYINT:
    case Types.BIGINT:
        empireType = DataType.INTEGER;
        break;
    case Types.VARCHAR:
        empireType = DataType.TEXT;
        break;
    case Types.DATE:
        empireType = DataType.DATE;
        break;
    case Types.TIMESTAMP:
    case Types.TIME:
        empireType = DataType.DATETIME;
        break;
    case Types.CHAR:
        empireType = DataType.CHAR;
        break;
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.REAL:
        empireType = DataType.FLOAT;
        break;
    case Types.DECIMAL:
    case Types.NUMERIC:
        empireType = DataType.DECIMAL;
        break;
    case Types.BIT:
    case Types.BOOLEAN:
        empireType = DataType.BOOL;
        break;
    case Types.CLOB:
    case Types.LONGVARCHAR:
        empireType = DataType.CLOB;
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
    case Types.BLOB:
        empireType = DataType.BLOB;
        break;
    default:
        empireType = DataType.UNKNOWN;
        log.warn("SQL column type " + sqlType + " not supported.");
    }
    log.debug("Mapping date type " + String.valueOf(sqlType) + " to " + empireType);
    return empireType;
}