List of usage examples for java.sql PreparedStatement setTime
void setTime(int parameterIndex, java.sql.Time x) throws SQLException;
java.sql.Time
value. From source file:org.apache.phoenix.end2end.DateTimeIT.java
@Test public void testTimestamp() throws Exception { String updateStmt = "upsert into " + tableName + " (" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_TIMESTAMP) " + "VALUES (?, ?, ?)"; // Override value that was set at creation time Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection upsertConn = DriverManager.getConnection(url, props); upsertConn.setAutoCommit(true); // Test auto commit PreparedStatement stmt = upsertConn.prepareStatement(updateStmt); stmt.setString(1, tenantId);//from w ww.j av a 2 s .c o m stmt.setString(2, ROW4); Timestamp tsValue1 = new Timestamp(5000); byte[] ts1 = PTimestamp.INSTANCE.toBytes(tsValue1); stmt.setTimestamp(3, tsValue1); stmt.execute(); Connection conn1 = DriverManager.getConnection(url, props); TestUtil.analyzeTable(conn1, tableName); conn1.close(); updateStmt = "upsert into " + tableName + " (" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_TIMESTAMP," + " A_TIME) " + "VALUES (?, ?, ?, ?)"; stmt = upsertConn.prepareStatement(updateStmt); stmt.setString(1, tenantId); stmt.setString(2, ROW5); Timestamp tsValue2 = new Timestamp(5000); tsValue2.setNanos(200); byte[] ts2 = PTimestamp.INSTANCE.toBytes(tsValue2); stmt.setTimestamp(3, tsValue2); stmt.setTime(4, new Time(tsValue2.getTime())); stmt.execute(); upsertConn.close(); assertTrue(TestUtil.compare(CompareOp.GREATER, new ImmutableBytesWritable(ts2), new ImmutableBytesWritable(ts1))); assertFalse(TestUtil.compare(CompareOp.GREATER, new ImmutableBytesWritable(ts1), new ImmutableBytesWritable(ts1))); String query = "SELECT entity_id, a_timestamp, a_time FROM " + tableName + " WHERE organization_id=? and a_timestamp > ?"; Connection conn = DriverManager.getConnection(url, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setTimestamp(2, new Timestamp(5000)); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(rs.getString(1), ROW5); assertEquals(rs.getTimestamp("A_TIMESTAMP"), tsValue2); assertEquals(rs.getTime("A_TIME"), new Time(tsValue2.getTime())); assertFalse(rs.next()); } finally { conn.close(); } }
From source file:org.apache.sqoop.TestExportUsingProcedure.java
public static void insertFunctiontestDatesAndTimes(int id, String msg, final Date date, final Time time) throws SQLException { insertFunction(id, msg, new SetExtraArgs() { @Override/*from w ww . j a v a 2s . c om*/ public void set(PreparedStatement on) throws SQLException { on.setDate(3, date); on.setTime(4, time); } }); }
From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java
/** * Return a Prepared statement for the given Statement object, which is ready to be executed * * @param stmnt SQL stataement to be executed * @param con The connection to be used * @param msgCtx Current message context * @return a PreparedStatement/*w ww . java 2s . c o m*/ * @throws SQLException on error */ protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx) throws SQLException { SynapseLog synLog = getLog(msgCtx); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Getting a connection from DataSource " + getDSName() + " and preparing statement : " + stmnt.getRawStatement()); } if (con == null) { String msg = "Connection from DataSource " + getDSName() + " is null."; log.error(msg); throw new SynapseException(msg); } if (dataSource instanceof BasicDataSource) { BasicDataSource basicDataSource = (BasicDataSource) dataSource; int numActive = basicDataSource.getNumActive(); int numIdle = basicDataSource.getNumIdle(); String connectionId = Integer.toHexString(con.hashCode()); DBPoolView dbPoolView = getDbPoolView(); if (dbPoolView != null) { dbPoolView.setNumActive(numActive); dbPoolView.setNumIdle(numIdle); dbPoolView.updateConnectionUsage(connectionId); } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("[ DB Connection : " + con + " ]"); synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]"); synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]"); synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]"); } } PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement()); // set parameters if any List<Statement.Parameter> params = stmnt.getParameters(); int column = 1; for (Statement.Parameter param : params) { if (param == null) { continue; } String value = (param.getPropertyName() != null ? param.getPropertyName() : param.getXpath().stringValueOf(msgCtx)); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : " + param.getType() + "(see java.sql.Types for valid " + "types)"); } switch (param.getType()) { // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: { if (value != null && value.length() != 0) { ps.setString(column++, value); } else { ps.setString(column++, null); } break; } case Types.NUMERIC: case Types.DECIMAL: { if (value != null && value.length() != 0) { ps.setBigDecimal(column++, new BigDecimal(value)); } else { ps.setBigDecimal(column++, null); } break; } case Types.BIT: { if (value != null && value.length() != 0) { ps.setBoolean(column++, Boolean.parseBoolean(value)); } else { ps.setNull(column++, Types.BIT); } break; } case Types.TINYINT: { if (value != null && value.length() != 0) { ps.setByte(column++, Byte.parseByte(value)); } else { ps.setNull(column++, Types.TINYINT); } break; } case Types.SMALLINT: { if (value != null && value.length() != 0) { ps.setShort(column++, Short.parseShort(value)); } else { ps.setNull(column++, Types.SMALLINT); } break; } case Types.INTEGER: { if (value != null && value.length() != 0) { ps.setInt(column++, Integer.parseInt(value)); } else { ps.setNull(column++, Types.INTEGER); } break; } case Types.BIGINT: { if (value != null && value.length() != 0) { ps.setLong(column++, Long.parseLong(value)); } else { ps.setNull(column++, Types.BIGINT); } break; } case Types.REAL: { if (value != null && value.length() != 0) { ps.setFloat(column++, Float.parseFloat(value)); } else { ps.setNull(column++, Types.REAL); } break; } case Types.FLOAT: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.FLOAT); } break; } case Types.DOUBLE: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.DOUBLE); } break; } // skip BINARY, VARBINARY and LONGVARBINARY case Types.DATE: { if (value != null && value.length() != 0) { ps.setDate(column++, Date.valueOf(value)); } else { ps.setNull(column++, Types.DATE); } break; } case Types.TIME: { if (value != null && value.length() != 0) { ps.setTime(column++, Time.valueOf(value)); } else { ps.setNull(column++, Types.TIME); } break; } case Types.TIMESTAMP: { if (value != null && value.length() != 0) { ps.setTimestamp(column++, Timestamp.valueOf(value)); } else { ps.setNull(column++, Types.TIMESTAMP); } break; } // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT default: { String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : " + column + " and statement : " + stmnt.getRawStatement() + " used by a DB mediator against DataSource : " + getDSName() + " (see java.sql.Types for valid type values)"; handleException(msg, msgCtx); } } } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement() + " against DataSource : " + getDSName()); } return ps; }
From source file:org.apache.tajo.catalog.store.AbstractDBStore.java
@Override public List<PartitionDescProto> getPartitionsByAlgebra(PartitionsByAlgebraProto request) throws UndefinedDatabaseException, UndefinedTableException, UndefinedPartitionMethodException, UnsupportedException {//from w w w . ja v a 2 s . c om Connection conn = null; PreparedStatement pstmt = null; ResultSet res = null; int currentIndex = 1; String selectStatement = null; Pair<String, List<PartitionFilterSet>> pair = null; List<PartitionDescProto> partitions = new ArrayList<>(); List<PartitionFilterSet> filterSets = null; int databaseId = getDatabaseId(request.getDatabaseName()); int tableId = getTableId(databaseId, request.getDatabaseName(), request.getTableName()); if (!existPartitionMethod(request.getDatabaseName(), request.getTableName())) { throw new UndefinedPartitionMethodException(request.getTableName()); } try { TableDescProto tableDesc = getTable(request.getDatabaseName(), request.getTableName()); pair = getSelectStatementAndPartitionFilterSet(tableDesc.getTableName(), tableDesc.getPartition().getExpressionSchema().getFieldsList(), request.getAlgebra()); selectStatement = pair.getFirst(); filterSets = pair.getSecond(); conn = getConnection(); pstmt = conn.prepareStatement(selectStatement); // Set table id by force because first parameter of all direct sql is table id pstmt.setInt(currentIndex, tableId); currentIndex++; for (PartitionFilterSet filter : filterSets) { // Set table id by force because all filters have table id as first parameter. pstmt.setInt(currentIndex, tableId); currentIndex++; for (Pair<Type, Object> parameter : filter.getParameters()) { switch (parameter.getFirst()) { case BOOLEAN: pstmt.setBoolean(currentIndex, (Boolean) parameter.getSecond()); break; case INT8: pstmt.setLong(currentIndex, (Long) parameter.getSecond()); break; case FLOAT8: pstmt.setDouble(currentIndex, (Double) parameter.getSecond()); break; case DATE: pstmt.setDate(currentIndex, (Date) parameter.getSecond()); break; case TIMESTAMP: pstmt.setTimestamp(currentIndex, (Timestamp) parameter.getSecond()); break; case TIME: pstmt.setTime(currentIndex, (Time) parameter.getSecond()); break; default: pstmt.setString(currentIndex, (String) parameter.getSecond()); break; } currentIndex++; } } res = pstmt.executeQuery(); while (res.next()) { PartitionDescProto.Builder builder = PartitionDescProto.newBuilder(); builder.setId(res.getInt(COL_PARTITIONS_PK)); builder.setPartitionName(res.getString("PARTITION_NAME")); builder.setPath(res.getString("PATH")); builder.setNumBytes(res.getLong(COL_PARTITION_BYTES)); partitions.add(builder.build()); } } catch (SQLException se) { throw new TajoInternalError(se); } finally { CatalogUtil.closeQuietly(pstmt, res); } return partitions; }
From source file:org.dspace.storage.rdbms.DatabaseManager.java
/** * Iterate over the given parameters and add them to the given prepared statement. * Only a select number of datatypes are supported by the JDBC driver. * * @param statement/*from w ww .j av a2 s. c om*/ * The unparameterized statement. * @param parameters * The parameters to be set on the statement. */ protected static void loadParameters(PreparedStatement statement, Object[] parameters) throws SQLException { statement.clearParameters(); int idx = 1; for (Object parameter : parameters) { if (parameter instanceof String) { statement.setString(idx, (String) parameter); } else if (parameter instanceof Long) { statement.setLong(idx, ((Long) parameter).longValue()); } else if (parameter instanceof Integer) { statement.setInt(idx, ((Integer) parameter).intValue()); } else if (parameter instanceof Short) { statement.setShort(idx, ((Short) parameter).shortValue()); } else if (parameter instanceof Date) { statement.setDate(idx, (Date) parameter); } else if (parameter instanceof Time) { statement.setTime(idx, (Time) parameter); } else if (parameter instanceof Timestamp) { statement.setTimestamp(idx, (Timestamp) parameter); } else if (parameter instanceof Double) { statement.setDouble(idx, ((Double) parameter).doubleValue()); } else if (parameter instanceof Float) { statement.setFloat(idx, ((Float) parameter).floatValue()); } else if (parameter == null) { throw new SQLException("Attempting to insert null value into SQL query."); } else { throw new SQLException("Attempting to insert unknown datatype (" + parameter.getClass().getName() + ") into SQL statement."); } idx++; } }
From source file:org.dspace.storage.rdbms.DatabaseManager.java
private static void loadParameters(PreparedStatement statement, Collection<ColumnInfo> columns, TableRow row) throws SQLException { int count = 0; for (ColumnInfo info : columns) { count++;/*from w ww . ja v a2 s .com*/ String column = info.getCanonicalizedName(); int jdbctype = info.getType(); if (row.isColumnNull(column)) { statement.setNull(count, jdbctype); } else { switch (jdbctype) { case Types.BIT: statement.setBoolean(count, row.getBooleanColumn(column)); break; case Types.INTEGER: if (isOracle) { statement.setLong(count, row.getLongColumn(column)); } else { statement.setInt(count, row.getIntColumn(column)); } break; case Types.NUMERIC: case Types.DECIMAL: statement.setLong(count, row.getLongColumn(column)); // FIXME should be BigDecimal if TableRow supported that break; case Types.BIGINT: statement.setLong(count, row.getLongColumn(column)); break; case Types.CLOB: if (isOracle) { // Support CLOBs in place of TEXT columns in Oracle statement.setString(count, row.getStringColumn(column)); } else { throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } break; case Types.VARCHAR: statement.setString(count, row.getStringColumn(column)); break; case Types.DATE: statement.setDate(count, new java.sql.Date(row.getDateColumn(column).getTime())); break; case Types.TIME: statement.setTime(count, new Time(row.getDateColumn(column).getTime())); break; case Types.TIMESTAMP: statement.setTimestamp(count, new Timestamp(row.getDateColumn(column).getTime())); break; default: throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } } } }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
/** * Iterate over the given parameters and add them to the given prepared statement. * Only a select number of datatypes are supported by the JDBC driver. * * @param statement//from w ww . j av a 2 s . co m * The unparameterized statement. * @param parameters * The parameters to be set on the statement. */ @Mock protected static void loadParameters(PreparedStatement statement, Object[] parameters) throws SQLException { statement.clearParameters(); for (int i = 0; i < parameters.length; i++) { // Select the object we are setting. Object parameter = parameters[i]; int idx = i + 1; // JDBC starts counting at 1. if (parameter == null) { throw new SQLException("Attempting to insert null value into SQL query."); } if (parameter instanceof String) { statement.setString(idx, (String) parameters[i]); } else if (parameter instanceof Integer) { int ii = ((Integer) parameter).intValue(); statement.setInt(idx, ii); } else if (parameter instanceof Double) { double d = ((Double) parameter).doubleValue(); statement.setDouble(idx, d); } else if (parameter instanceof Float) { float f = ((Float) parameter).floatValue(); statement.setFloat(idx, f); } else if (parameter instanceof Short) { short s = ((Short) parameter).shortValue(); statement.setShort(idx, s); } else if (parameter instanceof Long) { long l = ((Long) parameter).longValue(); statement.setLong(idx, l); } else if (parameter instanceof Date) { Date date = (Date) parameter; statement.setDate(idx, date); } else if (parameter instanceof Time) { Time time = (Time) parameter; statement.setTime(idx, time); } else if (parameter instanceof Timestamp) { Timestamp timestamp = (Timestamp) parameter; statement.setTimestamp(idx, timestamp); } else { throw new SQLException("Attempting to insert unknown datatype (" + parameter.getClass().getName() + ") into SQL statement."); } } }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
@Mock private static void loadParameters(PreparedStatement statement, Collection<ColumnInfo> columns, TableRow row) throws SQLException { int count = 0; for (ColumnInfo info : columns) { count++;/* ww w.j a va 2s . c o m*/ String column = info.getName(); int jdbctype = info.getType(); if (row.isColumnNull(column)) { statement.setNull(count, jdbctype); } else { switch (jdbctype) { case Types.BIT: case Types.BOOLEAN: statement.setBoolean(count, row.getBooleanColumn(column)); break; case Types.INTEGER: if (isOracle) { statement.setLong(count, row.getLongColumn(column)); } else { statement.setInt(count, row.getIntColumn(column)); } break; case Types.NUMERIC: case Types.DECIMAL: statement.setLong(count, row.getLongColumn(column)); // FIXME should be BigDecimal if TableRow supported that break; case Types.BIGINT: statement.setLong(count, row.getLongColumn(column)); break; case Types.CLOB: if (isOracle) { // Support CLOBs in place of TEXT columns in Oracle statement.setString(count, row.getStringColumn(column)); } else { throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } break; case Types.VARCHAR: statement.setString(count, row.getStringColumn(column)); break; case Types.DATE: statement.setDate(count, new java.sql.Date(row.getDateColumn(column).getTime())); break; case Types.TIME: statement.setTime(count, new Time(row.getDateColumn(column).getTime())); break; case Types.TIMESTAMP: statement.setTimestamp(count, new Timestamp(row.getDateColumn(column).getTime())); break; default: throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } } } }
From source file:org.ojbc.adapters.analyticaldatastore.dao.AnalyticalDatastoreDAOImpl.java
@Override public Integer saveIncident(final Incident inboundIncident) { log.debug("Inserting row into Incident table: " + inboundIncident.toString()); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { String incidentInsertStatement = ""; String[] insertArgs = null; if (inboundIncident.getIncidentID() == null) { incidentInsertStatement = "INSERT into INCIDENT (ReportingAgencyID, IncidentCaseNumber," + "IncidentLocationLatitude, IncidentLocationLongitude, IncidentLocationStreetAddress,IncidentLocationTown,IncidentDate,IncidentTime,ReportingSystem,RecordType) values (?,?,?,?,?,?,?,?,?,?)"; insertArgs = new String[] { "ReportingAgencyID", "IncidentCaseNumber" + "IncidentLocationLatitude", "IncidentLocationLongitude", "IncidentLocationStreetAddress", "IncidentLocationTown", "IncidentDate", "IncidentTime", "ReportingSystem", "RecordType" }; } else { incidentInsertStatement = "INSERT into INCIDENT (ReportingAgencyID, IncidentCaseNumber," + "IncidentLocationLatitude, IncidentLocationLongitude, IncidentLocationStreetAddress,IncidentLocationTown,IncidentDate,IncidentTime,ReportingSystem,RecordType, IncidentID) values (?,?,?,?,?,?,?,?,?,?,?)"; insertArgs = new String[] { "ReportingAgencyID", "IncidentCaseNumber" + "IncidentLocationLatitude", "IncidentLocationLongitude", "IncidentLocationStreetAddress", "IncidentLocationTown", "IncidentDate", "IncidentTime", "ReportingSystem", "RecordType", "IncidentID" }; }//from w ww .j a v a 2 s . c om PreparedStatement ps = connection.prepareStatement(incidentInsertStatement, insertArgs); if (inboundIncident.getReportingAgencyID() != null) { ps.setInt(1, inboundIncident.getReportingAgencyID()); } else { ps.setNull(1, java.sql.Types.NULL); } ps.setString(2, inboundIncident.getIncidentCaseNumber()); ps.setBigDecimal(3, inboundIncident.getIncidentLocationLatitude()); ps.setBigDecimal(4, inboundIncident.getIncidentLocationLongitude()); ps.setString(5, inboundIncident.getIncidentLocationStreetAddress()); ps.setString(6, inboundIncident.getIncidentLocationTown()); ps.setDate(7, new java.sql.Date(inboundIncident.getIncidentDate().getTime())); ps.setTime(8, new java.sql.Time(inboundIncident.getIncidentDate().getTime())); ps.setString(9, inboundIncident.getReportingSystem()); ps.setString(10, String.valueOf(inboundIncident.getRecordType())); if (inboundIncident.getIncidentID() != null) { ps.setInt(11, inboundIncident.getIncidentID()); } return ps; } }, keyHolder); Integer returnValue = null; if (inboundIncident.getIncidentID() != null) { returnValue = inboundIncident.getIncidentID(); } else { returnValue = keyHolder.getKey().intValue(); } return returnValue; }
From source file:org.ojbc.adapters.analyticaldatastore.dao.AnalyticalDatastoreDAOImpl.java
@Override public Integer saveArrest(final Arrest arrest) { log.debug("Inserting row into Arrest table"); final String arrestInsertStatement = "INSERT into ARREST ( PersonID,IncidentID,ArrestDate,ArrestTime,ArrestingAgencyName, ReportingSystem) values (?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(arrestInsertStatement, new String[] { "PersonID", "IncidentID", "ArrestDate", "ArrestTime", "ArrestingAgencyName", "ReportingSystem" }); ps.setInt(1, arrest.getPersonID()); ps.setInt(2, arrest.getIncidentID()); ps.setDate(3, new java.sql.Date(arrest.getArrestDate().getTime())); ps.setTime(4, new java.sql.Time(arrest.getArrestDate().getTime())); ps.setString(5, arrest.getArrestingAgencyName()); ps.setString(6, arrest.getReportingSystem()); return ps; }/*from w w w. ja va 2s. co m*/ }, keyHolder); return keyHolder.getKey().intValue(); }