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.apache.syncope.core.util.ImportExport.java

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

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

    final Table table = getTable(tableName);

    for (int i = 0; i < attrs.getLength(); i++) {
        Integer colType = table.getColumn(QualifiedDBIdentifier.newColumn(attrs.getQName(i))).getType();
        if (colType == null) {
            LOG.warn("No column type found for {}", attrs.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }//w  ww . ja v  a  2 s.  c om

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

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

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

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

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

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

        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            try {
                query.setParameter(i + 1, Hex.decode(attrs.getValue(i)));
            } catch (IllegalArgumentException e) {
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.BLOB:
            try {
                query.setParameter(i + 1, Hex.decode(attrs.getValue(i)));
            } catch (IllegalArgumentException e) {
                LOG.warn("Error decoding hex string to specify a blob parameter", e);
                query.setParameter(i + 1, attrs.getValue(i));
            } catch (Exception e) {
                LOG.warn("Error creating a new blob parameter", e);
            }
            break;

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

From source file:com.squid.core.jdbc.formatter.DefaultJDBCDataFormatter.java

public String getColumnFormat(int colType, int precision, int scale) {
    String stringFormat = null;/*from  w w w.jav  a2s . co  m*/
    switch (colType) {

    case Types.DATE:
        stringFormat = formatter.getDateFormat();
        break;
    case Types.TIME:
        break;
    case Types.TIMESTAMP:
        stringFormat = formatter.getTimestampFormat();
        break;
    }
    return stringFormat;
}

From source file:org.efaps.db.wrapper.AbstractSQLInsertUpdate.java

/**
 * Defines a new column <code>_columnName</code> with {@link Timestamp}
 * <code>_value</code> within this SQL insert / update statement.
 *
 * @param _columnName   name of the column
 * @param _value        value of the column
 * @return this SQL statement/*from  www  . j av  a2s  .com*/
 */
@SuppressWarnings("unchecked")
public STMT column(final String _columnName, final Timestamp _value) {
    this.columnWithValues
            .add(new AbstractSQLInsertUpdate.AbstractColumnWithValue<Timestamp>(_columnName, _value) {
                @Override
                public void set(final int _index, final PreparedStatement _stmt) throws SQLException {
                    if (getValue() == null) {
                        _stmt.setNull(_index, Types.TIMESTAMP);
                    } else {
                        _stmt.setTimestamp(_index, getValue());
                    }
                }
            });
    return (STMT) this;
}

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

/**
 *  ExecuteQuery will attempt execute the query passed to it against the
 *  existing database connection.  If no connection exists then no action
 *  is taken.//from   w  w w  . j  a v a 2  s  . co  m
 *  The results from the query are extracted and cached locally, thus
 *  applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed
 * @param  con  the connection the query is to be executed against
 *
 * @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("Invalid sql generated.  PieDataSet requires 2 columns only");
        }

        int columnType = metaData.getColumnType(2);
        double value = Double.NaN;
        while (resultSet.next()) {
            Comparable key = resultSet.getString(1);
            switch (columnType) {
            case Types.NUMERIC:
            case Types.REAL:
            case Types.INTEGER:
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.DECIMAL:
            case Types.BIGINT:
                value = resultSet.getDouble(2);
                setValue(key, value);
                break;

            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                Timestamp date = resultSet.getTimestamp(2);
                value = date.getTime();
                setValue(key, value);
                break;

            default:
                System.err.println("JDBCPieDataset - unknown data type");
                break;
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info

    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
    }
}

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

/**
 * Batch insert StepExecutions//  w  ww.  ja v  a  2s. c  om
 * @see StepExecutionDao#saveStepExecutions(Collection)
 */
@Override
public void saveStepExecutions(final Collection<StepExecution> stepExecutions) {
    Assert.notNull(stepExecutions, "Attempt to save a null collection of step executions");

    if (!stepExecutions.isEmpty()) {
        final Iterator<StepExecution> iterator = stepExecutions.iterator();
        getJdbcTemplate().batchUpdate(getQuery(SAVE_STEP_EXECUTION), new BatchPreparedStatementSetter() {

            @Override
            public int getBatchSize() {
                return stepExecutions.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                StepExecution stepExecution = iterator.next();
                List<Object[]> parameters = buildStepExecutionParameters(stepExecution);
                Object[] parameterValues = parameters.get(0);
                Integer[] parameterTypes = (Integer[]) parameters.get(1);
                for (int indx = 0; indx < parameterValues.length; indx++) {
                    switch (parameterTypes[indx]) {
                    case Types.INTEGER:
                        ps.setInt(indx + 1, (Integer) parameterValues[indx]);
                        break;
                    case Types.VARCHAR:
                        ps.setString(indx + 1, (String) parameterValues[indx]);
                        break;
                    case Types.TIMESTAMP:
                        if (parameterValues[indx] != null) {
                            ps.setTimestamp(indx + 1,
                                    new Timestamp(((java.util.Date) parameterValues[indx]).getTime()));
                        } else {
                            ps.setNull(indx + 1, Types.TIMESTAMP);
                        }
                        break;
                    case Types.BIGINT:
                        ps.setLong(indx + 1, (Long) parameterValues[indx]);
                        break;
                    default:
                        throw new IllegalArgumentException(
                                "unsupported SQL parameter type for step execution field index " + i);
                    }
                }
            }
        });
    }
}

From source file:org.eclipse.ecr.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java

@Override
public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column)
        throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
    case Types.CLOB:
        setToPreparedStatementString(ps, index, value, column);
        return;//from   ww w  . ja  va  2 s  .  com
    case Types.BIT:
        ps.setBoolean(index, ((Boolean) value).booleanValue());
        return;
    case Types.SMALLINT:
        ps.setInt(index, ((Long) value).intValue());
        return;
    case Types.INTEGER:
    case Types.BIGINT:
        ps.setLong(index, ((Long) value).longValue());
        return;
    case Types.DOUBLE:
        ps.setDouble(index, ((Double) value).doubleValue());
        return;
    case Types.TIMESTAMP:
        setToPreparedStatementTimestamp(ps, index, value, column);
        return;
    case Types.ARRAY:
        Array array = createArrayOf(Types.VARCHAR, (Object[]) value, ps.getConnection());
        ps.setArray(index, array);
        return;
    case Types.OTHER:
        if (column.getType() == ColumnType.FTSTORED) {
            ps.setString(index, (String) value);
            return;
        }
        throw new SQLException("Unhandled type: " + column.getType());
    default:
        throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.db.dialect.DialectOracle.java

@Override
public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column)
        throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
    case Types.CLOB:
        String v;/*w  w  w.j av  a2s . c o m*/
        if (column.getType() == ColumnType.BLOBID) {
            v = ((Binary) value).getDigest();
        } else {
            v = (String) value;
        }
        ps.setString(index, v);
        break;
    case Types.BIT:
        ps.setBoolean(index, ((Boolean) value).booleanValue());
        return;
    case Types.TINYINT:
    case Types.SMALLINT:
        ps.setInt(index, ((Long) value).intValue());
        return;
    case Types.INTEGER:
    case Types.BIGINT:
        ps.setLong(index, ((Long) value).longValue());
        return;
    case Types.DOUBLE:
        ps.setDouble(index, ((Double) value).doubleValue());
        return;
    case Types.TIMESTAMP:
        Calendar cal = (Calendar) value;
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        ps.setTimestamp(index, ts, cal); // cal passed for timezone
        return;
    // case Types.OTHER:
    // if (column.getType() == Type.FTSTORED) {
    // ps.setString(index, (String) value);
    // return;
    // }
    // throw new SQLException("Unhandled type: " + column.getType());
    default:
        throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
    }
}

From source file:org.traccar.database.QueryBuilder.java

public QueryBuilder setDate(String name, Date value) throws SQLException {
    for (int i : indexes(name)) {
        try {/*from www  .  j ava 2 s  . c o m*/
            if (value == null) {
                statement.setNull(i, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i, new Timestamp(value.getTime()));
            }
        } catch (SQLException error) {
            statement.close();
            connection.close();
            throw error;
        }
    }
    return this;
}

From source file:ca.nrc.cadc.cred.server.CertificateDAO.java

public void put(X509CertificateChain chain) {
    Profiler profiler = new Profiler(this.getClass());
    String hashKey = chain.getHashKey();
    String canonDn = AuthenticationUtil.canonizeDistinguishedName(chain.getPrincipal().getName());
    Date expDate = chain.getExpiryDate();
    String certChainStr = chain.certificateString();
    byte[] bytesPrivateKey = chain.getPrivateKey().getEncoded();
    //TODO just for testing - padded with zeros
    byte[] testBytesPrivateKey = Arrays.copyOf(bytesPrivateKey, bytesPrivateKey.length + 1);
    testBytesPrivateKey[testBytesPrivateKey.length - 1] = 1;
    String csr = chain.getCsrString();

    JdbcTemplate jdbc = new JdbcTemplate(config.getDataSource());
    if (recordExists(hashKey)) {
        String sql = "update " + config.getTable()
                + " set canon_dn = ?, exp_date = ?, cert_chain = ?, private_key = ?, csr = ? where hash_dn=?";
        Object[] args = new Object[] { canonDn, expDate, certChainStr, testBytesPrivateKey, csr, hashKey };
        int[] argTypes = new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.VARBINARY,
                Types.VARCHAR, Types.VARCHAR };
        jdbc.update(sql, args, argTypes);
    } else {//from  w w w.  j a  v a 2 s . c om
        String sql = "insert into " + config.getTable()
                + " (canon_dn, exp_date, cert_chain, private_key, csr, hash_dn) values (?,?,?,?,?,?)";
        Object[] args = new Object[] { canonDn, expDate, certChainStr, testBytesPrivateKey, csr, hashKey };
        int[] argTypes = new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.VARBINARY,
                Types.VARCHAR, Types.VARCHAR };

        jdbc.update(sql, args, argTypes);
    }
    profiler.checkpoint("put");
}

From source file:org.dashbuilder.dataprovider.backend.sql.JDBCUtils.java

public static ColumnType calculateType(int sqlDataType) {
    switch (sqlDataType) {

    // Category-like columns.
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.NCHAR:
    case Types.NVARCHAR:
    case Types.BIT:
    case Types.BOOLEAN: {
        return ColumnType.LABEL;
    }/*from   www .j av a  2  s  . com*/

    // Text-like columns.
    case Types.LONGVARCHAR:
    case Types.LONGNVARCHAR: {
        return ColumnType.TEXT;
    }

    // Number-like columns.
    case Types.TINYINT:
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.NUMERIC:
    case Types.REAL:
    case Types.SMALLINT: {
        return ColumnType.NUMBER;
    }

    // Date-like columns.
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP: {
        return ColumnType.DATE;
    }

    /*case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
    case Types.NULL:
    case Types.OTHER:
    case Types.JAVA_OBJECT:
    case Types.DISTINCT:
    case Types.STRUCT:
    case Types.ARRAY:
    case Types.BLOB:
    case Types.CLOB:
    case Types.REF:
    case Types.ROWID:
    case Types.SQLXML:
    case Types.DATALINK:*/

    // Unsupported (see above) types are treated as a text values.
    default: {
        return ColumnType.TEXT;
    }
    }
}