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:com.mapd.utility.SQLImporter.java

private String getColType(int cType, int precision, int scale) {
    if (precision > 19) {
        precision = 19;/*from w  w  w  .  j  ava2 s  .c o  m*/
    }
    if (scale > 19) {
        scale = 18;
    }
    switch (cType) {
    case java.sql.Types.TINYINT:
    case java.sql.Types.SMALLINT:
        return ("SMALLINT");
    case java.sql.Types.INTEGER:
        return ("INTEGER");
    case java.sql.Types.BIGINT:
        return ("BIGINT");
    case java.sql.Types.FLOAT:
        return ("FLOAT");
    case java.sql.Types.DECIMAL:
        return ("DECIMAL(" + precision + "," + scale + ")");
    case java.sql.Types.DOUBLE:
        return ("DOUBLE");
    case java.sql.Types.REAL:
        return ("REAL");
    case java.sql.Types.NUMERIC:
        return ("NUMERIC(" + precision + "," + scale + ")");
    case java.sql.Types.TIME:
        return ("TIME");
    case java.sql.Types.TIMESTAMP:
        return ("TIMESTAMP");
    case java.sql.Types.DATE:
        return ("DATE");
    case java.sql.Types.BOOLEAN:
    case java.sql.Types.BIT: // deal with postgress treating boolean as bit... this will bite me
        return ("BOOLEAN");
    case java.sql.Types.NVARCHAR:
    case java.sql.Types.VARCHAR:
    case java.sql.Types.NCHAR:
    case java.sql.Types.CHAR:
    case java.sql.Types.LONGVARCHAR:
    case java.sql.Types.LONGNVARCHAR:
        return ("TEXT ENCODING DICT");
    default:
        throw new AssertionError("Column type " + cType + " not Supported");
    }
}

From source file:org.apache.oozie.command.SchemaCheckXCommand.java

private String getSQLTypeFromInt(int t) {
    switch (t) {/*from  www  . j a v  a  2  s.c  o m*/
    case Types.BIT:
        return "BIT";
    case Types.TINYINT:
        return "TINYINT";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT";
    case Types.REAL:
        return "REAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.CHAR:
        return "CHAR";
    case Types.VARCHAR:
        return "VARCHAR";
    case Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case Types.DATE:
        return "DATE";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.BINARY:
        return "BINARY";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NULL:
        return "NULL";
    case Types.OTHER:
        return "OTHER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.DISTINCT:
        return "DISTINCT";
    case Types.STRUCT:
        return "STRUCT";
    case Types.ARRAY:
        return "ARRAY";
    case Types.BLOB:
        return "BLOB";
    case Types.CLOB:
        return "CLOB";
    case Types.REF:
        return "REF";
    case Types.DATALINK:
        return "DATALINK";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.ROWID:
        return "ROWID";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.SQLXML:
        return "SQLXML";
    default:
        return "unknown";
    }
}

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

/**
 * Adds DBColumn object to the given DBTable. The DBColumn is created from
 * the given ResultSet/*from   w  ww  .  ja v  a  2 s .  co  m*/
 */
private DBTableColumn addColumn(DBTable t, ResultSet rs) throws SQLException {
    String name = rs.getString("COLUMN_NAME");
    DataType empireType = getEmpireDataType(rs.getInt("DATA_TYPE"));

    double colSize = rs.getInt("COLUMN_SIZE");
    if (empireType == DataType.DECIMAL || empireType == DataType.FLOAT) { // decimal digits
        int decimalDig = rs.getInt("DECIMAL_DIGITS");
        if (decimalDig > 0) { // parse
            try {
                int intSize = rs.getInt("COLUMN_SIZE");
                colSize = Double.parseDouble(String.valueOf(intSize) + '.' + decimalDig);
            } catch (Exception e) {
                log.error("Failed to parse decimal digits for column " + name);
            }
        }
        // make integer?
        if (colSize < 1.0d) { // Turn into an integer
            empireType = DataType.INTEGER;
        }
    }

    // mandatory field?
    boolean required = false;
    String defaultValue = rs.getString("COLUMN_DEF");
    if (rs.getString("IS_NULLABLE").equalsIgnoreCase("NO"))
        required = true;

    // The following is a hack for MySQL which currently gets sent a string "CURRENT_TIMESTAMP" from the Empire-db driver for MySQL.
    // This will avoid the driver problem because CURRENT_TIMESTAMP in the db will just do the current datetime.
    // Essentially, Empire-db needs the concept of default values of one type that get mapped to another.
    // In this case, MySQL "CURRENT_TIMESTAMP" for Types.TIMESTAMP needs to emit from the Empire-db driver the null value and not "CURRENT_TIMESTAMP".
    if (rs.getInt("DATA_TYPE") == Types.TIMESTAMP && defaultValue != null
            && defaultValue.equals("CURRENT_TIMESTAMP")) {
        required = false; // It is in fact not required even though MySQL schema is required because it has a default value. Generally, should Empire-db emit (required && defaultValue != null) to truly determine if a column is required?
        defaultValue = null; // If null (and required per schema?) MySQL will apply internal default value.
    }

    // AUTOINC indicator is not in java.sql.Types but rather meta data from DatabaseMetaData.getColumns()
    // getEmpireDataType() above is not enough to support AUTOINC as it will only return DataType.INTEGER
    DataType originalType = empireType;
    ResultSetMetaData metaData = rs.getMetaData();
    int colCount = metaData.getColumnCount();
    String colName;
    for (int i = 1; i <= colCount; i++) {
        colName = metaData.getColumnName(i);
        // MySQL matches on IS_AUTOINCREMENT column.
        // SQL Server matches on TYPE_NAME column with identity somewhere in the string value.
        if ((colName.equalsIgnoreCase("IS_AUTOINCREMENT") && rs.getString(i).equalsIgnoreCase("YES"))
                || (colName.equals("TYPE_NAME") && rs.getString(i).matches(".*(?i:identity).*"))) {
            empireType = DataType.AUTOINC;

        }
    }

    // Move from the return statement below so we can add
    // some AUTOINC meta data to the column to be used by
    // the ParserUtil and ultimately the template.
    log.info("\tCOLUMN:\t" + name + " (" + empireType + ")");
    DBTableColumn col = t.addColumn(name, empireType, colSize, required, defaultValue);

    // We still need to know the base data type for this AUTOINC
    // because the Record g/setters need to know this, right?
    // So, let's add it as meta data every time the column is AUTOINC
    // and reference it in the template.
    if (empireType.equals(DataType.AUTOINC))
        col.setAttribute("AutoIncDataType", originalType);
    return col;

}

From source file:org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.java

/**
 * Convenience method that inserts an individual records into the
 * JobParameters table.//from   w  w w.ja  va  2  s.  c o m
 */
private void insertParameter(Long executionId, ParameterType type, String key, Object value,
        boolean identifying) {

    Object[] args = new Object[0];
    int[] argTypes = new int[] { Types.BIGINT, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP,
            Types.BIGINT, Types.DOUBLE, Types.CHAR };

    String identifyingFlag = identifying ? "Y" : "N";

    if (type == ParameterType.STRING) {
        args = new Object[] { executionId, key, type, value, new Timestamp(0L), 0L, 0D, identifyingFlag };
    } else if (type == ParameterType.LONG) {
        args = new Object[] { executionId, key, type, "", new Timestamp(0L), value, new Double(0),
                identifyingFlag };
    } else if (type == ParameterType.DOUBLE) {
        args = new Object[] { executionId, key, type, "", new Timestamp(0L), 0L, value, identifyingFlag };
    } else if (type == ParameterType.DATE) {
        args = new Object[] { executionId, key, type, "", value, 0L, 0D, identifyingFlag };
    }

    getJdbcTemplate().update(getQuery(CREATE_JOB_PARAMETERS), args, argTypes);
}

From source file:org.executequery.gui.importexport.AbstractImportExportWorker.java

/**
 * Sets the specified value in the specified position for the
 * specified java.sql.Type within the prepared statement.
 *
 * @param value - the value// w  w  w  .j  a  v  a 2  s  .  com
 * @param index - the position within the statement
 * @param sqlType - the SQL type
 * @param trim - whether to trim the whitespace from the value
 * @param df - the DataFormat object for date values
 */
protected void setValue(String value, int index, int sqlType, boolean trim, DateFormat df) throws Exception {

    if (value == null) {

        prepStmnt.setNull(index, sqlType);

    } else {

        switch (sqlType) {

        case Types.TINYINT:
            byte _byte = Byte.valueOf(value).byteValue();
            prepStmnt.setShort(index, _byte);
            break;

        case Types.BIGINT:
            long _long = Long.valueOf(value).longValue();
            prepStmnt.setLong(index, _long);
            break;

        case Types.SMALLINT:
            short _short = Short.valueOf(value).shortValue();
            prepStmnt.setShort(index, _short);
            break;

        case Types.LONGVARCHAR:
        case Types.CHAR:
        case Types.VARCHAR:
            if (trim) {
                value = value.trim();
            }
            prepStmnt.setString(index, value);
            break;

        case Types.BIT:
        case Types.BOOLEAN:

            String booleanValue = value;
            if ("t".equalsIgnoreCase(value)) {

                booleanValue = "true";

            } else if ("f".equalsIgnoreCase(value)) {

                booleanValue = "false";
            }

            boolean _boolean = Boolean.valueOf(booleanValue).booleanValue();
            prepStmnt.setBoolean(index, _boolean);
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
            prepStmnt.setBigDecimal(index, new BigDecimal(value));
            break;

        case Types.REAL:
            float _float = Float.valueOf(value).floatValue();
            prepStmnt.setFloat(index, _float);
            break;

        case Types.FLOAT:
        case Types.DOUBLE:
            prepStmnt.setDouble(index, Double.parseDouble(value));
            break;

        case Types.INTEGER:
            prepStmnt.setInt(index, Integer.parseInt(value));
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            // if the date format is null, insert as a char value
            if (df != null) {
                java.util.Date j_datetime = df.parse(value);
                prepStmnt.setDate(index, new java.sql.Date(j_datetime.getTime()));
            } else {
                try {
                    prepStmnt.setObject(index, value, sqlType);
                    /*
                    if (sqlType == Types.TIMESTAMP) {
                        prepStmnt.setTimestamp(index,
                                java.sql.Timestamp.valueOf(value));
                    }
                    else if (sqlType == Types.TIME) {
                        prepStmnt.setTime(index,
                                java.sql.Time.valueOf(value));
                    }
                    else {
                        prepStmnt.setDate(index,
                                java.sql.Date.valueOf(value));
                    }
                     */
                }
                // want a more useful message here than what will likely
                // be returned due to internal driver code on formatting
                // a SQL date value from string
                // (ie. could be parsing error, number format etc...)
                catch (Exception e) {
                    throw new IllegalArgumentException("[ " + MiscUtils.getExceptionName(e) + " ] "
                            + getBundle().getString("AbstractImportExportWorker.dateConversionError"));
                }

            }
            break;

        case Types.LONGVARBINARY:
        case Types.BINARY:
        case Types.BLOB:
        case Types.CLOB:
            prepStmnt.setBytes(index, Base64.decode(value));
            break;

        default:
            prepStmnt.setObject(index, value);
            break;
        }
    }
}

From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java

protected Object getObjectValue(String value, Column column, BinaryEncoding encoding, boolean useVariableDates,
        boolean fitToColumn) throws DecoderException {
    Object objectValue = value;/*w  w  w .  j a  v  a2s . co  m*/
    int type = column.getMappedTypeCode();
    if ((value == null || (getDdlBuilder().getDatabaseInfo().isEmptyStringNulled() && value.equals("")))
            && column.isRequired() && column.isOfTextType()) {
        objectValue = REQUIRED_FIELD_NULL_SUBSTITUTE;
    }
    if (value != null) {
        if (type == Types.DATE || type == Types.TIMESTAMP || type == Types.TIME) {
            objectValue = parseDate(type, value, useVariableDates);
        } else if (type == Types.CHAR) {
            String charValue = value.toString();
            if ((StringUtils.isBlank(charValue)
                    && getDdlBuilder().getDatabaseInfo().isBlankCharColumnSpacePadded())
                    || (StringUtils.isNotBlank(charValue)
                            && getDdlBuilder().getDatabaseInfo().isNonBlankCharColumnSpacePadded())) {
                objectValue = StringUtils.rightPad(value.toString(), column.getSizeAsInt(), ' ');
            }
        } else if (type == Types.BIGINT) {
            objectValue = parseBigInteger(value);
        } else if (type == Types.INTEGER || type == Types.SMALLINT || type == Types.BIT
                || type == Types.TINYINT) {
            objectValue = parseInteger(value);
        } else if (type == Types.NUMERIC || type == Types.DECIMAL || type == Types.FLOAT || type == Types.DOUBLE
                || type == Types.REAL) {
            objectValue = parseBigDecimal(value);
        } else if (type == Types.BOOLEAN) {
            objectValue = value.equals("1") ? Boolean.TRUE : Boolean.FALSE;
        } else if (!(column.getJdbcTypeName() != null
                && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOMETRY))
                && !(column.getJdbcTypeName() != null
                        && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOGRAPHY))
                && (type == Types.BLOB || type == Types.LONGVARBINARY || type == Types.BINARY
                        || type == Types.VARBINARY ||
                        // SQLServer ntext type
                        type == -10)) {
            if (encoding == BinaryEncoding.NONE) {
                objectValue = value.getBytes();
            } else if (encoding == BinaryEncoding.BASE64) {
                objectValue = Base64.decodeBase64(value.getBytes());
            } else if (encoding == BinaryEncoding.HEX) {
                objectValue = Hex.decodeHex(value.toCharArray());
            }
        } else if (type == Types.ARRAY) {
            objectValue = createArray(column, value);
        }
    }
    if (objectValue instanceof String) {
        String stringValue = cleanTextForTextBasedColumns((String) objectValue);
        int size = column.getSizeAsInt();
        if (fitToColumn && size > 0 && stringValue.length() > size) {
            stringValue = stringValue.substring(0, size);
        }
        objectValue = stringValue;
    }

    return objectValue;

}

From source file:org.apache.nifi.processors.standard.TestPutSQL.java

@Test
public void testUsingTimestampValuesWithFormatAttribute()
        throws InitializationException, ProcessException, SQLException, IOException, ParseException {
    final TestRunner runner = TestRunners.newTestRunner(PutSQL.class);
    try (final Connection conn = service.getConnection()) {
        try (final Statement stmt = conn.createStatement()) {
            stmt.executeUpdate(// w  ww .  ja  v  a2 s .c  o  m
                    "CREATE TABLE TIMESTAMPTEST2 (id integer primary key, ts1 timestamp, ts2 timestamp)");
        }
    }

    runner.addControllerService("dbcp", service);
    runner.enableControllerService(service);
    runner.setProperty(PutSQL.CONNECTION_POOL, "dbcp");

    final String dateStr = "2002-02-02T12:02:02+00:00";
    final long dateInt = 1012651322000L;

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.TIMESTAMP));
    attributes.put("sql.args.1.value", dateStr);
    attributes.put("sql.args.1.format", "ISO_OFFSET_DATE_TIME");
    attributes.put("sql.args.2.type", String.valueOf(Types.TIMESTAMP));
    attributes.put("sql.args.2.value", dateStr);
    attributes.put("sql.args.2.format", "yyyy-MM-dd'T'HH:mm:ssXXX");

    runner.enqueue("INSERT INTO TIMESTAMPTEST2 (ID, ts1, ts2) VALUES (1, ?, ?)".getBytes(), attributes);
    runner.run();

    runner.assertAllFlowFilesTransferred(PutSQL.REL_SUCCESS, 1);

    try (final Connection conn = service.getConnection()) {
        try (final Statement stmt = conn.createStatement()) {
            final ResultSet rs = stmt.executeQuery("SELECT * FROM TIMESTAMPTEST2");
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertEquals(dateInt, rs.getTimestamp(2).getTime());
            assertEquals(dateInt, rs.getTimestamp(3).getTime());
            assertFalse(rs.next());
        }
    }
}

From source file:com.liferay.portal.upgrade.util.Table.java

public void setColumn(PreparedStatement ps, int index, Integer type, String value) throws Exception {

    int t = type.intValue();

    int paramIndex = index + 1;

    if (t == Types.BIGINT) {
        ps.setLong(paramIndex, GetterUtil.getLong(value));
    } else if (t == Types.BOOLEAN) {
        ps.setBoolean(paramIndex, GetterUtil.getBoolean(value));
    } else if ((t == Types.CLOB) || (t == Types.VARCHAR)) {
        value = StringUtil.replace(value, SAFE_CHARS[1], SAFE_CHARS[0]);

        ps.setString(paramIndex, value);
    } else if (t == Types.DOUBLE) {
        ps.setDouble(paramIndex, GetterUtil.getDouble(value));
    } else if (t == Types.FLOAT) {
        ps.setFloat(paramIndex, GetterUtil.getFloat(value));
    } else if (t == Types.INTEGER) {
        ps.setInt(paramIndex, GetterUtil.getInteger(value));
    } else if (t == Types.SMALLINT) {
        ps.setShort(paramIndex, GetterUtil.getShort(value));
    } else if (t == Types.TIMESTAMP) {
        if (StringPool.NULL.equals(value)) {
            ps.setTimestamp(paramIndex, null);
        } else {//from   w  ww  . java2  s  .  com
            DateFormat df = DateUtil.getISOFormat();

            ps.setTimestamp(paramIndex, new Timestamp(df.parse(value).getTime()));
        }
    } else {
        throw new UpgradeException("Upgrade code using unsupported class type " + type);
    }
}

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

@Override
public Long getPreferenceTime(int tenantId, Date cutoffDate, long userID, long itemID, int actionTypeId)
        throws TasteException {
    Object[] args = new Object[] { tenantId, cutoffDate, userID, itemID, actionTypeId };
    int[] argTypes = new int[] { Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER, Types.INTEGER };
    try {//from w ww.j  a  v  a  2s .c o  m
        return getJdbcTemplate().queryForObject(getPreferenceTimeQuery, args, argTypes, Date.class).getTime();
    } catch (EmptyResultDataAccessException e) {
        //as mahout/taste doesn't catch the NoSuchUserException, we don't throw it to save time
        logger.warn("An error occurred!", e);
        return null;
    }
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Get one value into DbValue from ResultSet
 * //ww w.  j  ava2 s  .c  o m
 * @param rs
 * @param value
 * @throws WaarpDatabaseSqlException
 */
static public void getTrueValue(ResultSet rs, DbValue value) throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.LONGVARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.BIT:
            value.value = rs.getBoolean(value.column);
            break;
        case Types.TINYINT:
            value.value = rs.getByte(value.column);
            break;
        case Types.SMALLINT:
            value.value = rs.getShort(value.column);
            break;
        case Types.INTEGER:
            value.value = rs.getInt(value.column);
            break;
        case Types.BIGINT:
            value.value = rs.getLong(value.column);
            break;
        case Types.REAL:
            value.value = rs.getFloat(value.column);
            break;
        case Types.DOUBLE:
            value.value = rs.getDouble(value.column);
            break;
        case Types.VARBINARY:
            value.value = rs.getBytes(value.column);
            break;
        case Types.DATE:
            value.value = rs.getDate(value.column);
            break;
        case Types.TIMESTAMP:
            value.value = rs.getTimestamp(value.column);
            break;
        case Types.CLOB:
            value.value = rs.getClob(value.column).getCharacterStream();
            break;
        case Types.BLOB:
            value.value = rs.getBlob(value.column).getBinaryStream();
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " for " + value.column);
        }
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Getting values in error: " + value.type + " for " + value.column,
                e);
    }
}