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.sakaiproject.webservices.SakaiReport.java

protected String toJsonString(ResultSet rs) throws SQLException, JSONException {
    ResultSetMetaData rsmd = rs.getMetaData();
    JSONArray array = new JSONArray();
    int numColumns = rsmd.getColumnCount();

    while (rs.next()) {

        JSONObject obj = new JSONObject();
        for (int i = 1; i < numColumns + 1; i++) {

            String column_label = rsmd.getColumnLabel(i);

            LOG.debug("Column Name=" + column_label + ",type=" + rsmd.getColumnType(i));

            switch (rsmd.getColumnType(i)) {
            case Types.ARRAY:
                obj.put(column_label, rs.getArray(i));
                break;
            case Types.BIGINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.BOOLEAN:
                obj.put(column_label, rs.getBoolean(i));
                break;
            case Types.BLOB:
                obj.put(column_label, rs.getBlob(i));
                break;
            case Types.DOUBLE:
                obj.put(column_label, rs.getDouble(i));
                break;
            case Types.FLOAT:
                obj.put(column_label, rs.getFloat(i));
                break;
            case Types.INTEGER:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.NVARCHAR:
                obj.put(column_label, rs.getNString(i));
                break;
            case Types.VARCHAR:
                obj.put(column_label, rs.getString(i));
                break;
            case Types.TINYINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.SMALLINT:
                obj.put(column_label, rs.getInt(i));
                break;
            case Types.DATE:
                obj.put(column_label, rs.getDate(i));
                break;
            case Types.TIMESTAMP:
                obj.put(column_label, rs.getTimestamp(i));
                break;
            default:
                obj.put(column_label, rs.getObject(i));
                break;
            }/*from  ww  w .ja v a2 s.c  om*/

        }
        array.put(obj);

    }
    return array.toString();
}

From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java

protected void applyParameters(PreparedStatement statement, ParameterValueList parameters)
        throws SQLException, SenderException {
    // statement.clearParameters();

    /*//w  w  w.  j ava 2  s  .c  o m
          // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation.
          int senderParameterCount = parameters.size();
          int statementParameterCount = statement.getParameterMetaData().getParameterCount();
          if (statementParameterCount<senderParameterCount) {
             throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]");
          }
    */

    for (int i = 0; i < parameters.size(); i++) {
        ParameterValue pv = parameters.getParameterValue(i);
        String paramType = pv.getDefinition().getType();
        Object value = pv.getValue();
        //      log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]");

        if (Parameter.TYPE_DATE.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.DATE);
            } else {
                statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_DATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIME);
            } else {
                statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_NUMBER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.NUMERIC);
            } else {
                statement.setDouble(i + 1, ((Number) value).doubleValue());
            }
        } else if (Parameter.TYPE_INTEGER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.INTEGER);
            } else {
                statement.setInt(i + 1, (Integer) value);
            }
        } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
            if (value instanceof FileInputStream) {
                FileInputStream fis = (FileInputStream) value;
                long len = 0;
                try {
                    len = fis.getChannel().size();
                } catch (IOException e) {
                    log.warn(getLogPrefix() + "could not determine file size", e);
                }
                statement.setBinaryStream(i + 1, fis, (int) len);
            } else if (value instanceof ByteArrayInputStream) {
                ByteArrayInputStream bais = (ByteArrayInputStream) value;
                long len = bais.available();
                statement.setBinaryStream(i + 1, bais, (int) len);
            } else {
                throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                        + "] for parameter [" + pv.getDefinition().getName() + "]");
            }
        } else if ("string2bytes".equals(paramType)) {
            statement.setBytes(i + 1, ((String) value).getBytes());
        } else if ("bytes".equals(paramType)) {
            statement.setBytes(i + 1, (byte[]) value);
        } else {
            statement.setString(i + 1, (String) value);
        }
    }
}

From source file:org.jumpmind.db.model.Column.java

/**
 * Tries to parse the default value of the column and returns it as an
 * object of the corresponding java type. If the value could not be parsed,
 * then the original definition is returned.
 * /*w w  w  .  j  ava 2s  .  c o m*/
 * @return The parsed default value
 */
public Object getParsedDefaultValue() {
    if ((defaultValue != null) && (defaultValue.length() > 0)) {
        try {
            switch (mappedTypeCode) {
            case Types.TINYINT:
            case Types.SMALLINT:
                return new Short(defaultValue);
            case Types.INTEGER:
                try {
                    return new Integer(defaultValue);
                } catch (NumberFormatException e) {
                    return new Long(defaultValue);
                }
            case Types.BIGINT:
                return new Long(defaultValue);
            case Types.DECIMAL:
            case Types.NUMERIC:
                return new BigDecimal(defaultValue);
            case Types.REAL:
                return new Float(defaultValue);
            case Types.DOUBLE:
            case Types.FLOAT:
                return new Double(defaultValue);
            case Types.DATE:
                return Date.valueOf(defaultValue);
            case Types.TIME:
                return Time.valueOf(defaultValue);
            case Types.TIMESTAMP:
                return Timestamp.valueOf(defaultValue);
            case Types.BIT:
                return FormatUtils.toBoolean(defaultValue);
            default:
                if (PlatformUtils.supportsJava14JdbcTypes()
                        && (mappedTypeCode == PlatformUtils.determineBooleanTypeCode())) {
                    return FormatUtils.toBoolean(defaultValue);
                }
                break;
            }
        } catch (NumberFormatException ex) {
            return null;
        } catch (IllegalArgumentException ex) {
            return null;
        }
    }
    return defaultValue;
}

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

public void save(Node node) {
    if (!updateNode(node)) {
        sqlTemplate.update(getSql("insertNodeSql"),
                new Object[] { node.getNodeGroupId(), node.getExternalId(), node.getDatabaseType(),
                        node.getDatabaseVersion(), node.getSchemaVersion(), node.getSymmetricVersion(),
                        node.getSyncUrl(), new Date(), node.isSyncEnabled() ? 1 : 0,
                        AppUtils.getTimezoneOffset(), node.getBatchToSendCount(), node.getBatchInErrorCount(),
                        node.getCreatedAtNodeId(), node.getDeploymentType(), node.getNodeId() },
                new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                        Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP, Types.INTEGER, Types.VARCHAR,
                        Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
    }//from   w  ww  . j  ava 2 s .  c o  m
}

From source file:org.jumpmind.metl.core.runtime.component.Sorter.java

protected void createDatabase() {
    if (databasePlatform == null) {
        ResettableBasicDataSource ds = new ResettableBasicDataSource();
        ds.setDriverClassName(Driver.class.getName());
        ds.setMaxActive(1);//from   w  ww. j  a va 2 s. c om
        ds.setInitialSize(1);
        ds.setMinIdle(1);
        ds.setMaxIdle(1);
        databaseName = UUID.randomUUID().toString();
        ds.setUrl("jdbc:h2:mem:" + databaseName);
        databasePlatform = JdbcDatabasePlatformFactory.createNewPlatformInstance(ds, new SqlTemplateSettings(),
                true, false);

        Model inputModel = context.getFlowStep().getComponent().getInputModel();
        List<ModelEntity> entities = inputModel.getModelEntities();
        for (ModelEntity entity : entities) {
            Table table = new Table();
            table.setName(entity.getName() + "_1");
            List<ModelAttribute> attributes = entity.getModelAttributes();
            for (ModelAttribute attribute : attributes) {
                DataType dataType = attribute.getDataType();
                Column column = new Column(attribute.getName());
                if (dataType.isNumeric()) {
                    column.setTypeCode(Types.DECIMAL);
                } else if (dataType.isBoolean()) {
                    column.setTypeCode(Types.BOOLEAN);
                } else if (dataType.isTimestamp()) {
                    column.setTypeCode(Types.TIMESTAMP);
                } else if (dataType.isBinary()) {
                    column.setTypeCode(Types.BLOB);
                } else {
                    column.setTypeCode(Types.LONGVARCHAR);
                }

                column.setPrimaryKey(attribute.isPk());
                table.addColumn(column);
            }

            alterCaseToMatchLogicalCase(table);
            databasePlatform.createTables(false, false, table);
        }

        log(LogLevel.INFO, "Creating databasePlatform with the following url: %s", ds.getUrl());
    }
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insert(final OpenbareRuimte openbareRuimte) throws DAOException {
    try {//from   ww  w. j a  va2  s . c  o  m
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement("insert into bag_openbare_ruimte ("
                        + "bag_openbare_ruimte_id," + "aanduiding_record_inactief,"
                        + "aanduiding_record_correctie," + "openbare_ruimte_naam," + "officieel,"
                        + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek,"
                        + "openbare_ruimte_type," + "bron_documentdatum," + "bron_documentnummer,"
                        + "openbareruimte_status," + "bag_woonplaats_id," + "verkorte_openbare_ruimte_naam"
                        + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                ps.setLong(1, openbareRuimte.getIdentificatie());
                ps.setInt(2, openbareRuimte.getAanduidingRecordInactief().ordinal());
                ps.setLong(3, openbareRuimte.getAanduidingRecordCorrectie());
                ps.setString(4, openbareRuimte.getOpenbareRuimteNaam());
                ps.setInt(5, openbareRuimte.getOfficieel().ordinal());
                ps.setTimestamp(6, new Timestamp(openbareRuimte.getBegindatumTijdvakGeldigheid().getTime()));
                if (openbareRuimte.getEinddatumTijdvakGeldigheid() == null)
                    ps.setNull(7, Types.TIMESTAMP);
                else
                    ps.setTimestamp(7, new Timestamp(openbareRuimte.getEinddatumTijdvakGeldigheid().getTime()));
                ps.setInt(8, openbareRuimte.getInOnderzoek().ordinal());
                ps.setInt(9, openbareRuimte.getOpenbareRuimteType().ordinal());
                ps.setDate(10, new Date(openbareRuimte.getDocumentdatum().getTime()));
                ps.setString(11, openbareRuimte.getDocumentnummer());
                ps.setInt(12, openbareRuimte.getOpenbareruimteStatus().ordinal());
                ps.setLong(13, openbareRuimte.getGerelateerdeWoonplaats());
                ps.setString(14, openbareRuimte.getVerkorteOpenbareRuimteNaam());
                return ps;
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting openbare ruimte: " + openbareRuimte.getIdentificatie(), e);
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

/**
 * Determines if there are invalid values specified in the initial offset value
 * for columns./*from www.  ja v a2s.c o m*/
 */
//@VisibleForTesting
void checkForInvalidInitialOffsetValues(PushSource.Context context, List<Stage.ConfigIssue> issues,
        String qualifiedTableName, LinkedHashMap<String, Integer> offsetColumnToType,
        Map<String, String> offsetColumnToStartOffset) throws StageException {
    List<String> invalidInitialOffsetFieldAndValue = new ArrayList<>();
    offsetColumnToType.forEach((offsetColumn, offsetSqlType) -> {
        String initialOffsetValue = offsetColumnToStartOffset.get(offsetColumn);
        try {
            if (jdbcUtil.isSqlTypeOneOf(offsetSqlType, Types.DATE, Types.TIME, Types.TIMESTAMP)) {
                Long.valueOf(initialOffsetValue); //NOSONAR
            } else {
                //Use native field conversion strategy to conver string to specify type and get value
                Field.create(OffsetQueryUtil.SQL_TYPE_TO_FIELD_TYPE.get(offsetSqlType), initialOffsetValue)
                        .getValue();
            }
        } catch (IllegalArgumentException e) {
            LOG.error(Utils.format("Invalid Initial Offset Value {} for column {} in table {}",
                    initialOffsetValue, offsetColumn, qualifiedTableName), e);
            invalidInitialOffsetFieldAndValue.add(offsetColumn + " - " + initialOffsetValue);
        }
    });
    if (!invalidInitialOffsetFieldAndValue.isEmpty()) {
        throw new StageException(JdbcErrors.JDBC_72, qualifiedTableName,
                COMMA_JOINER.join(invalidInitialOffsetFieldAndValue));
    }
}

From source file:org.latticesoft.util.resource.dao.Param.java

private void setValueToStatement(Object o, PreparedStatement pstmt) throws SQLException {
    if (log.isDebugEnabled()) {
        log.debug(this.sqlIndex + "=" + o);
    }/*from  w w  w. j  a v  a 2s.c  o m*/
    switch (this.sqlType) {
    case Types.VARCHAR:
    case Types.CHAR:
        String s = (String) o;
        pstmt.setString(this.sqlIndex, s);
        break;
    case Types.BOOLEAN:
        if (o != null && o instanceof Boolean) {
            boolean b = ((Boolean) o).booleanValue();
            pstmt.setBoolean(this.sqlIndex, b);
        }
        break;
    case Types.INTEGER:
        if (o != null && o instanceof Integer) {
            int i = ((Integer) o).intValue();
            pstmt.setInt(this.sqlIndex, i);
        }
        break;
    case Types.SMALLINT:
        if (o != null && o instanceof Short) {
            short ss = ((Short) o).shortValue();
            pstmt.setShort(this.sqlIndex, ss);
        }
        break;
    case Types.TINYINT:
        if (o != null && o instanceof Byte) {
            byte bb = ((Byte) o).byteValue();
            pstmt.setByte(this.sqlIndex, bb);
        }
        break;
    case Types.BIGINT:
        if (o != null && o instanceof Long) {
            long l = ((Long) o).longValue();
            pstmt.setLong(this.sqlIndex, l);
        }
        break;
    case Types.DOUBLE:
        if (o != null && o instanceof Double) {
            double dd = ((Double) o).doubleValue();
            pstmt.setDouble(this.sqlIndex, dd);
        }
        break;
    case Types.FLOAT:
        if (o != null && o instanceof Float) {
            float f = ((Float) o).floatValue();
            pstmt.setFloat(this.sqlIndex, f);
        }
        break;
    case Types.NUMERIC:
        if (o != null && o instanceof BigDecimal) {
            BigDecimal bd = (BigDecimal) o;
            pstmt.setBigDecimal(this.sqlIndex, bd);
        }
        break;
    case Types.TIMESTAMP:
        if (o != null && o instanceof Timestamp) {
            Timestamp ts = (Timestamp) o;
            pstmt.setTimestamp(this.sqlIndex, ts);
        }
        break;
    case Types.NULL:
        if (log.isDebugEnabled()) {
            log.debug(this.sqlIndex + " IS NULL");
        }
        pstmt.setNull(this.sqlIndex, Types.NULL);
        break;
    default:
        if (o != null) {
            pstmt.setObject(this.sqlIndex, o);
        }
    }
}

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

@Test
public void testUsingTimestampValuesEpochAndString()
        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(//from   ww  w  .  ja  v  a  2s. co  m
                    "CREATE TABLE TIMESTAMPTEST1 (id integer primary key, ts1 timestamp, ts2 timestamp)");
        }
    }

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

    final String arg2TS = "2001-01-01 00:01:01.001";
    final String art3TS = "2002-02-02 12:02:02.002";
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    java.util.Date parsedDate = dateFormat.parse(arg2TS);

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.TIMESTAMP));
    attributes.put("sql.args.1.value", Long.toString(parsedDate.getTime()));
    attributes.put("sql.args.2.type", String.valueOf(Types.TIMESTAMP));
    attributes.put("sql.args.2.value", art3TS);

    runner.enqueue("INSERT INTO TIMESTAMPTEST1 (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 TIMESTAMPTEST1");
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertEquals(arg2TS, rs.getString(2));
            assertEquals(art3TS, rs.getString(3));
            assertFalse(rs.next());
        }
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public Map<String, String> getMinimumOffsetValues(Connection connection, String schema, String tableName,
        QuoteChar quoteChar, Collection<String> offsetColumnNames) throws SQLException {
    Map<String, String> minOffsetValues = new HashMap<>();
    final String qualifiedName = TableContextUtil.getQuotedQualifiedTableName(schema, tableName,
            quoteChar.getQuoteCharacter());
    for (String offsetColumn : offsetColumnNames) {
        final String minOffsetQuery = String.format(MIN_OFFSET_VALUE_QUERY, offsetColumn, qualifiedName);
        try (Statement st = connection.createStatement(); ResultSet rs = st.executeQuery(minOffsetQuery)) {
            if (rs.next()) {
                String minValue = null;
                final int colType = rs.getMetaData().getColumnType(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                switch (colType) {
                case Types.DATE:
                    java.sql.Date date = rs.getDate(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    if (date != null) {
                        minValue = String.valueOf(date.toInstant().toEpochMilli());
                    }/*  w w  w  . j a v a2 s  .c  o  m*/
                    break;
                case Types.TIME:
                    java.sql.Time time = rs.getTime(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    if (time != null) {
                        minValue = String.valueOf(time.toInstant().toEpochMilli());
                    }
                    break;
                case Types.TIMESTAMP:
                    Timestamp timestamp = rs.getTimestamp(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    if (timestamp != null) {
                        final Instant instant = timestamp.toInstant();
                        minValue = String.valueOf(instant.toEpochMilli());
                    }
                    break;
                default:
                    minValue = rs.getString(MIN_OFFSET_VALUE_QUERY_RESULT_SET_INDEX);
                    break;
                }
                if (minValue != null) {
                    minOffsetValues.put(offsetColumn, minValue);
                }
            } else {
                LOG.warn("Unable to get minimum offset value using query {}; result set had no rows",
                        minOffsetQuery);
            }
        }
    }

    return minOffsetValues;
}