public class MainClass { public static void main(String[] args) { java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); System.out.println("utilDate:" + utilDate); System.out.println("sqlDate:" + sqlDate); } }
private static Object convertDateValue(final Object value, final Class<?> convertType) { Date date = (Date) value; switch (convertType.getName()) { case "java.sql.Date": return new java.sql.Date(date.getTime()); case "java.sql.Time": return new Time(date.getTime()); case "java.sql.Timestamp": return new Timestamp(date.getTime()); default: throw new ShardingException("Unsupported Date type:%s", convertType); } } }
@Override public void write(PreparedStatement statement, int index, Date value) throws SQLException { int sqlType = getSqlType(); if (value == null) { statement.setNull(index, sqlType); } else { long time = value.getTime(); statement.setDate(index, new java.sql.Date(time)); } }
@Test public void testDateInList() throws Exception { String query = "SELECT entity_id FROM " + this.tableName + " WHERE a_date IN (?,?) AND a_integer < 4"; PreparedStatement statement = conn.prepareStatement(query); statement.setDate(1, new Date(0)); statement.setDate(2, date); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(ROW1, rs.getString(1)); assertFalse(rs.next()); }
@Test public void testIncBackupFileCreation() throws ParseException { // Test incremental file File bfile = new File("target/data/Keyspace1/Standard1/Keyspace1-Standard1-ia-5-Data.db"); RemoteBackupPath backupfile = injector.getInstance(RemoteBackupPath.class); backupfile.parseLocal(bfile, BackupFileType.SST); Assert.assertEquals(BackupFileType.SST, backupfile.type); Assert.assertEquals("Keyspace1", backupfile.keyspace); Assert.assertEquals("Standard1", backupfile.columnFamily); Assert.assertEquals("1234567", backupfile.token); Assert.assertEquals("fake-app", backupfile.clusterName); Assert.assertEquals(region, backupfile.region); Assert.assertEquals("casstestbackup", backupfile.baseDir); String datestr = DateUtil.formatyyyyMMddHHmm(new Date(bfile.lastModified())); Assert.assertEquals( "casstestbackup/" + region + "/fake-app/1234567/" + datestr + "/SST/Keyspace1/Standard1/Keyspace1-Standard1-ia-5-Data.db", backupfile.getRemotePath()); }
@Test public void testTimestampsInResponse() throws Exception { final ResultSet resultSet = client.createStatement().executeQuery( "SELECT __time, CAST(__time AS DATE) AS t2 FROM druid.foo LIMIT 1" ); Assert.assertEquals( ImmutableList.of( ImmutableMap.of( "__time", new Timestamp(DateTimes.of("2000-01-01T00:00:00.000Z").getMillis()), "t2", new Date(DateTimes.of("2000-01-01").getMillis()) ) ), getRows(resultSet) ); }
@Test public void testSubarrayObject() { final Object[] nullArray = null; final Object[] objectArray = {"a", "b", "c", "d", "e", "f"}; assertEquals("0 start, mid end", "abcd", StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4))); assertEquals("0 start, length end", "abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 0, objectArray.length))); assertEquals("mid start, mid end", "bcd", StringUtils.join(ArrayUtils.subarray(objectArray, 1, 4))); assertEquals("mid start, length end", "bcdef", final Date[] dateArray = {new java.sql.Date(new Date().getTime()), new Date(), new Date(), new Date(), new Date()};
ps.setString(paramIndex, inValue.toString()); ps.setString(paramIndex, strVal); if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Date) { ps.setDate(paramIndex, (java.sql.Date) inValue); ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime())); ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal); ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime())); ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal); ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime())); ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal); "Oracle".equals(ps.getConnection().getMetaData().getDatabaseProductName()))) { if (isStringValue(inValue.getClass())) { ps.setString(paramIndex, inValue.toString()); ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
@Test public void testSetParameterValueWithDateAndCalendar() throws SQLException { java.util.Calendar cal = new GregorianCalendar(); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, cal); verify(preparedStatement).setDate(1, new java.sql.Date(cal.getTime().getTime()), cal); }
@Test public void testDateType() { final long now = System.currentTimeMillis(); final java.sql.Date original = new java.sql.Date( now ); final java.sql.Date copy = new java.sql.Date( now ); Calendar cal = new GregorianCalendar(); cal.clear(); cal.setTimeInMillis( now ); cal.add( Calendar.YEAR, 1 ); final java.sql.Date different = new java.sql.Date( cal.getTime().getTime() ); runBasicTests( DateType.INSTANCE, original, copy, different ); }
@Signature public void bind(Environment env, int index, Memory value) throws SQLException { if (value.instanceOf(WrapTime.class)) { WrapTime time = value.toObject(WrapTime.class); statement.setDate(index + 1, new Date(time.getDate().getTime()), time.getCalendar()); } else if (value.instanceOf(Stream.class)) { statement.setBlob(index + 1, Stream.getInputStream(env, value)); } else if (value.toValue() instanceof BinaryMemory) { statement.setBytes(index + 1, value.getBinaryBytes(env.getDefaultCharset())); } else { if (value.isNull()) { statement.setNull(index + 1, Types.NULL); } else { switch (value.getRealType()) { case INT: statement.setLong(index + 1, value.toLong()); break; case DOUBLE: statement.setDouble(index + 1, value.toDouble()); break; case BOOL: statement.setBoolean(index + 1, value.toBoolean()); break; default: statement.setString(index + 1, value.toString()); } } } }
@Test public void execute_and_log_prepared_statement_with_parameters() throws Exception { logTester.setLevel(LoggerLevel.TRACE); Connection connection = mock(Connection.class); when(originDataSource.getConnection()).thenReturn(connection); String sqlWithParams = "insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?)"; int param1 = 42; String param2 = "plouf"; Date param3 = new Date(System.currentTimeMillis()); Timestamp param4 = new Timestamp(System.currentTimeMillis()); byte[] param5 = "blob".getBytes(UTF_8); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(connection.prepareStatement(sqlWithParams)).thenReturn(preparedStatement); when(preparedStatement.execute()).thenReturn(true); ProfiledDataSource ds = new ProfiledDataSource(originDataSource, ProfiledConnectionInterceptor.INSTANCE); assertThat(ds.getUrl()).isNull(); assertThat(ds.getConnection().getClientInfo()).isNull(); PreparedStatement preparedStatementProxy = ds.getConnection().prepareStatement(sqlWithParams); preparedStatementProxy.setInt(1, param1); preparedStatementProxy.setString(2, param2); preparedStatementProxy.setDate(3, param3); preparedStatementProxy.setTimestamp(4, param4); preparedStatementProxy.setBlob(5, new ByteArrayInputStream(param5)); assertThat(preparedStatementProxy.getConnection()).isNull(); assertThat(preparedStatementProxy.execute()).isTrue(); assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1); assertThat(logTester.logs(LoggerLevel.TRACE).get(0)) .contains("sql=insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?)") .contains("params=42, plouf"); }
@Test public void testSetParameterValueWithDateAndUtilDate() throws SQLException { java.util.Date date = new java.util.Date(1000); StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, date); verify(preparedStatement).setDate(1, new java.sql.Date(1000)); }
@Test public void testRow() { Row r1 = new Row(); r1.addField(new Field(AccumuloRowSerializer.getBlockFromArray(VARCHAR, ImmutableList.of("a", "b", "c")), new ArrayType(VARCHAR))); r1.addField(true, BOOLEAN); r1.addField(new Field(new Date(new GregorianCalendar(1999, 0, 1).getTime().getTime()), DATE)); r1.addField(123.45678, DOUBLE); r1.addField(new Field(123.45678f, REAL)); r1.addField(12345678, INTEGER); r1.addField(new Field(12345678L, BIGINT)); r1.addField(new Field((short) 12345, SMALLINT)); r1.addField(new GregorianCalendar(1999, 0, 1, 12, 30, 0).getTime().getTime(), TIME); r1.addField(new Field(new Timestamp(new GregorianCalendar(1999, 0, 1, 12, 30, 0).getTime().getTime()), TIMESTAMP)); r1.addField((byte) 123, TINYINT); r1.addField(new Field("O'Leary".getBytes(UTF_8), VARBINARY)); r1.addField("O'Leary", VARCHAR); r1.addField(null, VARCHAR); assertEquals(r1.length(), 14); assertEquals(r1.toString(), "(ARRAY ['a','b','c'],true,DATE '1999-01-01',123.45678,123.45678,12345678,12345678,12345,TIME '12:30:00',TIMESTAMP '1999-01-01 12:30:00.0',123,CAST('O''Leary' AS VARBINARY),'O''Leary',null)"); Row r2 = new Row(r1); assertEquals(r2, r1); }
protected void setObject(PreparedStatement statement, int i, Object value) throws SQLException { try { if (value instanceof InParameter) { InParameter p = (InParameter) value; if (p.getType() == Types.BLOB && p.getValue() instanceof InputStream) { statement.setBlob(i, (InputStream) p.getValue()); return; } if (p.getType() == Types.CLOB && p.getValue() instanceof Reader) { statement.setClob(i, (Reader) p.getValue()); return; } if (p.getType() == Types.DATE && p.getValue() instanceof java.util.Date && !(p.getValue() instanceof java.sql.Date)) { statement.setDate(i, new java.sql.Date(((java.util.Date) p.getValue()).getTime())); return; } if (p.getType() == Types.TIMESTAMP && p.getValue() instanceof java.util.Date && !(p.getValue() instanceof java.sql.Timestamp)) { statement.setTimestamp(i, new java.sql.Timestamp(((java.util.Date) p.getValue()).getTime())); return; } } if (value instanceof GString) { value = value.toString(); } super.setObject(statement, i, value); } catch (Exception e) { throw new SQLException("Can't set a parameter #" + i + " to value type " + (value == null ? "null" : value.getClass().getName()) + ": " + e.getMessage(), e); } } }
@SuppressWarnings({ "unchecked" }) public <X> X unwrap(Calendar value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( Calendar.class.isAssignableFrom( type ) ) { return (X) value; } if ( java.sql.Date.class.isAssignableFrom( type ) ) { return (X) new java.sql.Date( value.getTimeInMillis() ); } if ( java.sql.Time.class.isAssignableFrom( type ) ) { return (X) new java.sql.Time( value.getTimeInMillis() ); } if ( java.sql.Timestamp.class.isAssignableFrom( type ) ) { return (X) new java.sql.Timestamp( value.getTimeInMillis() ); } if ( java.util.Date.class.isAssignableFrom( type ) ) { return (X) new java.util.Date( value.getTimeInMillis() ); } throw unknownUnwrap( type ); }
@SuppressWarnings("unchecked") public Mock(MockType type) throws Exception { connection = mock(Connection.class); statement = mock(Statement.class); resultSet = mock(ResultSet.class); resultSetMetaData = mock(ResultSetMetaData.class); given(connection.createStatement()).willReturn(statement); given(statement.executeQuery(anyString())).willReturn(resultSet); given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.next()).willReturn(true, false); given(resultSet.getString(1)).willReturn("Bubba"); given(resultSet.getLong(2)).willReturn(22L); given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L)); given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException()); given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L)); given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56")); given(resultSet.wasNull()).willReturn(type == MockType.TWO); given(resultSetMetaData.getColumnCount()).willReturn(4); given(resultSetMetaData.getColumnLabel(1)).willReturn( type == MockType.THREE ? "Last Name" : "name"); given(resultSetMetaData.getColumnLabel(2)).willReturn("age"); given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date"); given(resultSetMetaData.getColumnLabel(4)).willReturn("balance"); jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false)); jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); jdbcTemplate.afterPropertiesSet(); }
@Test public void testUnfoundMultiColumnCaseStatement() throws Exception { String query = "SELECT entity_id, b_string FROM ATABLE WHERE organization_id=? and CASE WHEN a_integer = 1234 THEN 1 WHEN a_date < ? THEN y_integer WHEN x_integer = 4 THEN 4 ELSE 3 END = 4"; String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5 Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setDate(2, new Date(System.currentTimeMillis())); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(ROW8, rs.getString(1)); assertFalse(rs.next()); } finally { conn.close(); } }