@Override public int insertSubject(Subject subject, String start, String end) { subject.setCapacity(Integer.parseInt(subject.getCapacity_String().replace(",", ""))); subject.setLecture_totalday( Integer.parseInt(subject.getLecture_totalday_String().replace(",", ""))); subject.setTuition_fee(Integer.parseInt(subject.getTuition_fee_String().replace(",", ""))); Time start1 = Time.valueOf(start + ":00"); Time end1 = Time.valueOf(end + ":00"); long a = (end1.getTime() - start1.getTime()) / 1000; int time3 = (int) (subject.getLecture_totalday() * a); Subject subject2 = new Subject( subject.getSubject_id(), subject.getSubject_name(), subject.getCapacity(), subject.getSubject_explanation(), subject.getInstructional_objectives(), subject.getSubject_point(), subject.getLecture_target(), subject.getLecture_totalday(), subject.getTuition_fee(), subject.getLecture_content(), subject.getCenter_id(), start1, end1, time3 / 3600); return sqlSession.getMapper(SubjectDAO.class).insertSubject(subject2); }
public static int calculate(Time awal, Time akhir) { Long millis3 = (akhir.getTime() - awal.getTime()); Long hasil = millis3 / HOUR_IN_MILIS; if (millis3 % HOUR_IN_MILIS > 0) hasil++; return hasil.intValue(); }
public static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, Time time) { if (time.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time.getTime()); rbTime.extend(new IRubyObject[]{runtime.getModule("TimeFormatter")}); return rbTime; // SimpleDateFormat sdf = new SimpleDateFormat("HH-mm-ss"); // TODO proper format? // return runtime.newString(sdf.format(rbTime.getJavaDate())); }
private List<WebSocketChannelDTO> buildChannelDTOs(ResultSet rs) throws SQLException { ArrayList<WebSocketChannelDTO> channels = new ArrayList<>(); try { while (rs.next()) { WebSocketChannelDTO channel = new WebSocketChannelDTO(); channel.id = rs.getInt("channel_id"); channel.host = rs.getString("host"); channel.port = rs.getInt("port"); channel.url = rs.getString("url"); channel.startTimestamp = rs.getTimestamp("start_timestamp").getTime(); Time endTs = rs.getTime("end_timestamp"); channel.endTimestamp = (endTs != null) ? endTs.getTime() : null; channel.historyId = rs.getInt("history_id"); channels.add(channel); } } finally { rs.close(); } channels.trimToSize(); return channels; }
@Override public String translateLiteralTime(Time timeValue) { if (!hasTimeType()) { return translateLiteralTimestamp(new Timestamp(timeValue.getTime())); } return '\'' + formatDateValue(timeValue) + '\''; }
@Test public void testCalendar2Timestamp() { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(time); Time sqltime = sqlTimeConverter.convert(calendar); assertEquals(time, sqltime.getTime()); }
private static Time getTime(SQLDialect dialect, ResultSet rs, int index) throws SQLException { // SQLite's type affinity needs special care... if (dialect == SQLDialect.SQLITE) { String time = rs.getString(index); if (time != null) { return new Time(parse("HH:mm:ss", time)); } return null; } // Cubrid SQL dates are incorrectly fetched. Reset milliseconds... // See http://jira.cubrid.org/browse/APIS-159 // See https://sourceforge.net/apps/trac/cubridinterface/ticket/140 else if (dialect == CUBRID) { Time time = rs.getTime(index); if (time != null) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time.getTime()); cal.set(Calendar.MILLISECOND, 0); time = new Time(cal.getTimeInMillis()); } return time; } else { return rs.getTime(index); } }
@Nullable @Override public OffsetTime getValue(ResultSet rs, int startIndex) throws SQLException { Time time = rs.getTime(startIndex, utc()); return time != null ? OffsetTime.ofInstant(Instant.ofEpochMilli(time.getTime()), ZoneOffset.UTC) : null; }
private static Time shift(Time v) { if (v == null) { return null; } long time = v.getTime(); int offset = TimeZone.getDefault().getOffset(time); return new Time((time + offset) % DateTimeUtil.MILLIS_PER_DAY); }
/** * Convert the time using the specified calendar. * * @param x the time * @param calendar the calendar * @return the time */ public static ValueTime convertTime(Time x, Calendar calendar) { if (calendar == null) { throw DbException.getInvalidValueException("calendar", null); } Calendar cal = (Calendar) calendar.clone(); cal.setTimeInMillis(x.getTime()); long nanos = nanosFromCalendar(cal); return ValueTime.fromNanos(nanos); }
public static Long toEpochFormat(String mdate, int hour, int minute) throws ParseException { Date date = new Date(mdate); Time time = new Time(hour + 7, minute, 0); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MILLISECOND, (int) time.getTime()); return calendar.getTime().getTime(); }
@Override public int updateSubject(Subject subject, String start, String end) { subject.setCapacity(Integer.parseInt(subject.getCapacity_String().replace(",", ""))); subject.setLecture_totalday( Integer.parseInt(subject.getLecture_totalday_String().replace(",", ""))); subject.setTuition_fee(Integer.parseInt(subject.getTuition_fee_String().replace(",", ""))); Time start1 = null; Time end1 = null; if (start.length() < 7) { start1 = Time.valueOf(start + ":00"); } else { start1 = Time.valueOf(start); } if (end.length() < 7) { end1 = Time.valueOf(end + ":00"); } else { end1 = Time.valueOf(end); } long a = (end1.getTime() - start1.getTime()) / 1000; int b = (int) (subject.getLecture_totalday() * a); Subject subject2 = new Subject( subject.getSubject_id(), subject.getSubject_name(), subject.getCapacity(), subject.getSubject_explanation(), subject.getInstructional_objectives(), subject.getSubject_point(), subject.getLecture_target(), subject.getLecture_totalday(), subject.getTuition_fee(), subject.getLecture_content(), start1, end1, b / 3600); return sqlSession.getMapper(SubjectDAO.class).updateSubject(subject2); }
@Test public void testTimeConverter() { String sql = "select current_time as col1 from (values(0))"; Time sqlTime = sql2o.createQuery(sql).executeScalar(Time.class); assertThat(sqlTime, is(notNullValue())); assertTrue(sqlTime.getTime() > 0); Date date = sql2o.createQuery(sql).executeScalar(Date.class); assertThat(date, is(notNullValue())); LocalTime jodaTime = sql2o.createQuery(sql).executeScalar(LocalTime.class); assertTrue(jodaTime.getMillisOfDay() > 0); assertThat(jodaTime.getHourOfDay(), is(equalTo(new LocalTime().getHourOfDay()))); }
public void setTime(int parameterIndex, java.sql.Time x) throws SQLException { if (parameterIndex < 1 || parameterIndex > args.length) { throw new SQLException("bad parameter index"); } if (x == null) { args[parameterIndex - 1] = nullrepl ? "" : null; } else { if (conn.useJulian) { args[parameterIndex - 1] = java.lang.Double.toString(SQLite.Database.julian_from_long(x.getTime())); } else { args[parameterIndex - 1] = x.toString(); } } blobs[parameterIndex - 1] = false; }
@Override public User mapRow(ResultSet resultSet, int i) throws SQLException { User user = new User(); user.setId(new Long(resultSet.getLong("id"))); user.setEmail(resultSet.getString("email")); user.setPassword(resultSet.getString("password")); user.setAccountId(resultSet.getLong("account_id")); user.setFirstName(resultSet.getString("first_name")); user.setLastName(resultSet.getString("last_name")); user.setToken(resultSet.getString("token")); Time time = resultSet.getTime("last_Logged"); if (time != null) user.setLastLogged(new Date(time.getTime())); return user; }
@Test public void getTimeFromResultSet() throws SQLException, IOException { Time time = new Time(12, 0, 0); // noon long dateInMilliSeconds = time.getTime(); String[] expectedNames = {"Time", "Null"}; String[] realValues = {Long.toString(dateInMilliSeconds), null}; String[] expectedValues = {time.toString(), ""}; int[] expectedTypes = {Types.TIME, Types.TIME}; ResultSetMetaData metaData = MockResultSetMetaDataBuilder.buildMetaData(expectedNames, expectedTypes); ResultSet resultSet = MockResultSetBuilder.buildResultSet(metaData, realValues, expectedTypes); ResultSetHelperService service = new ResultSetHelperService(); String[] columnValues = service.getColumnValues(resultSet); assertArrayEquals(expectedValues, columnValues); }
public void printTime() { // The hour of day is required in order to describe the time of day. long milliseconds = time.getTime(); long dayTime = milliseconds % (86400000); int hours = Math.round(dayTime / 3600000); if (hours > 5 && hours < 12) { // Morning System.out.println(GameLocale.getString("TXT_KEY_TIME_DESCRIPTION_MORNING")); } else if (hours < 13) { // Noon System.out.println(GameLocale.getString("TXT_KEY_TIME_DESCRIPTION_NOON")); } else if (hours < 18) { // Afternoon System.out.println(GameLocale.getString("TXT_KEY_TIME_DESCRIPTION_AFTERNOON")); } else if (hours < 20) { // Evening System.out.println(GameLocale.getString("TXT_KEY_TIME_DESCRIPTION_EVENING")); } else { // Night System.out.println(GameLocale.getString("TXT_KEY_TIME_DESCRIPTION_NIGHT")); } }
public void testGetTime() throws Exception { con.createStatement() .executeUpdate( "INSERT INTO testtimezone(tstz,ts,t,tz) VALUES('2005-01-01 15:00:00 +0300', '2005-01-01 15:00:00', '15:00:00', '15:00:00 +0300')"); PreparedStatement ps = con.prepareStatement("SELECT tstz,ts,t,tz from testtimezone"); for (int i = 0; i < PREPARE_THRESHOLD; i++) { ResultSet rs = ps.executeQuery(); assertTrue(rs.next()); checkDatabaseContents( "SELECT tstz::text,ts::text,t::text,tz::text,d::text from testtimezone", new String[] { "2005-01-01 12:00:00+00", "2005-01-01 15:00:00", "15:00:00", "15:00:00+03" }); Time t; // timestamptz: 2005-01-01 15:00:00+03 t = rs.getTime(1); // 2005-01-01 13:00:00 +0100 -> 1970-01-01 13:00:00 +0100 assertEquals(43200000L, t.getTime()); t = rs.getTime(1, cUTC); // 2005-01-01 12:00:00 +0000 -> 1970-01-01 12:00:00 +0000 assertEquals(43200000L, t.getTime()); t = rs.getTime(1, cGMT03); // 2005-01-01 15:00:00 +0300 -> 1970-01-01 15:00:00 +0300 assertEquals(43200000L, t.getTime()); t = rs.getTime(1, cGMT05); // 2005-01-01 07:00:00 -0500 -> 1970-01-01 07:00:00 -0500 assertEquals(43200000L, t.getTime()); t = rs.getTime(1, cGMT13); // 2005-01-02 01:00:00 +1300 -> 1970-01-01 01:00:00 +1300 assertEquals(-43200000L, t.getTime()); // timestamp: 2005-01-01 15:00:00 t = rs.getTime(2); assertEquals(50400000L, t.getTime()); // 1970-01-01 15:00:00 +0100 t = rs.getTime(2, cUTC); assertEquals(54000000L, t.getTime()); // 1970-01-01 15:00:00 +0000 t = rs.getTime(2, cGMT03); assertEquals(43200000L, t.getTime()); // 1970-01-01 15:00:00 +0300 t = rs.getTime(2, cGMT05); assertEquals(72000000L, t.getTime()); // 1970-01-01 15:00:00 -0500 t = rs.getTime(2, cGMT13); assertEquals(7200000L, t.getTime()); // 1970-01-01 15:00:00 +1300 // time: 15:00:00 t = rs.getTime(3); assertEquals(50400000L, t.getTime()); // 1970-01-01 15:00:00 +0100 t = rs.getTime(3, cUTC); assertEquals(54000000L, t.getTime()); // 1970-01-01 15:00:00 +0000 t = rs.getTime(3, cGMT03); assertEquals(43200000L, t.getTime()); // 1970-01-01 15:00:00 +0300 t = rs.getTime(3, cGMT05); assertEquals(72000000L, t.getTime()); // 1970-01-01 15:00:00 -0500 t = rs.getTime(3, cGMT13); assertEquals(7200000L, t.getTime()); // 1970-01-01 15:00:00 +1300 // timetz: 15:00:00+03 t = rs.getTime(4); assertEquals(43200000L, t.getTime()); // 1970-01-01 13:00:00 +0100 t = rs.getTime(4, cUTC); assertEquals(43200000L, t.getTime()); // 1970-01-01 12:00:00 +0000 t = rs.getTime(4, cGMT03); assertEquals(43200000L, t.getTime()); // 1970-01-01 15:00:00 +0300 t = rs.getTime(4, cGMT05); assertEquals(43200000L, t.getTime()); // 1970-01-01 07:00:00 -0500 t = rs.getTime(4, cGMT13); assertEquals(-43200000L, t.getTime()); // 1970-01-01 01:00:00 +1300 rs.close(); } }
public static IRubyObject parse_time(Ruby runtime, Time tm) { RubyTime time = RubyTime.newTime(runtime, tm.getTime()); time.extend(new IRubyObject[] {runtime.getModule("TimeFormatter")}); return (time.getUSec() != 0) ? time : runtime.getNil(); }
@Test public void testSqlDate2Timestamp() { java.sql.Date date = new java.sql.Date(time); Time sqltime = sqlTimeConverter.convert(date); assertEquals(time, sqltime.getTime()); }
@Test public void testSqlTime2Timestamp() { Time sqltime2 = new Time(time); Time sqltime = sqlTimeConverter.convert(sqltime2); assertEquals(time, sqltime.getTime()); }
public static Object parseType(ResultSet result, Integer i, int type) throws SQLException, IOException, ParseException { logger.trace("i={} type={}", i, type); switch (type) { /** * The JDBC types CHAR, VARCHAR, and LONGVARCHAR are closely related. CHAR represents a * small, fixed-length character string, VARCHAR represents a small, variable-length * character string, and LONGVARCHAR represents a large, variable-length character string. */ case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: { return result.getString(i); } case Types.NCHAR: case Types.NVARCHAR: case Types.LONGNVARCHAR: { return result.getNString(i); } /** * The JDBC types BINARY, VARBINARY, and LONGVARBINARY are closely related. BINARY * represents a small, fixed-length binary value, VARBINARY represents a small, * variable-length binary value, and LONGVARBINARY represents a large, variable-length * binary value */ case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: { byte[] b = result.getBytes(i); return b; } /** * The JDBC type ARRAY represents the SQL3 type ARRAY. * * <p>An ARRAY value is mapped to an instance of the Array interface in the Java programming * language. If a driver follows the standard implementation, an Array object logically * points to an ARRAY value on the server rather than containing the elements of the ARRAY * object, which can greatly increase efficiency. The Array interface contains methods for * materializing the elements of the ARRAY object on the client in the form of either an * array or a ResultSet object. */ case Types.ARRAY: { Array arr = result.getArray(i); return arr == null ? null : arr.getArray(); } /** * The JDBC type BIGINT represents a 64-bit signed integer value between * -9223372036854775808 and 9223372036854775807. * * <p>The corresponding SQL type BIGINT is a nonstandard extension to SQL. In practice the * SQL BIGINT type is not yet currently implemented by any of the major databases, and we * recommend that its use be avoided in code that is intended to be portable. * * <p>The recommended Java mapping for the BIGINT type is as a Java long. */ case Types.BIGINT: { Object o = result.getLong(i); return result.wasNull() ? null : o; } /** * The JDBC type BIT represents a single bit value that can be zero or one. * * <p>SQL-92 defines an SQL BIT type. However, unlike the JDBC BIT type, this SQL-92 BIT * type can be used as a parameterized type to define a fixed-length binary string. * Fortunately, SQL-92 also permits the use of the simple non-parameterized BIT type to * represent a single binary digit, and this usage corresponds to the JDBC BIT type. * Unfortunately, the SQL-92 BIT type is only required in "full" SQL-92 and is currently * supported by only a subset of the major databases. Portable code may therefore prefer to * use the JDBC SMALLINT type, which is widely supported. */ case Types.BIT: { try { Object o = result.getInt(i); return result.wasNull() ? null : o; } catch (Exception e) { String exceptionClassName = e.getClass().getName(); // postgresql can not handle boolean, it will throw PSQLException, something like "Bad // value for type int : t" if ("org.postgresql.util.PSQLException".equals(exceptionClassName)) { return "t".equals(result.getString(i)); } throw new IOException(e); } } /** * The JDBC type BOOLEAN, which is new in the JDBC 3.0 API, maps to a boolean in the Java * programming language. It provides a representation of true and false, and therefore is a * better match than the JDBC type BIT, which is either 1 or 0. */ case Types.BOOLEAN: { return result.getBoolean(i); } /** * The JDBC type BLOB represents an SQL3 BLOB (Binary Large Object). * * <p>A JDBC BLOB value is mapped to an instance of the Blob interface in the Java * programming language. If a driver follows the standard implementation, a Blob object * logically points to the BLOB value on the server rather than containing its binary data, * greatly improving efficiency. The Blob interface provides methods for materializing the * BLOB data on the client when that is desired. */ case Types.BLOB: { Blob blob = result.getBlob(i); if (blob != null) { long n = blob.length(); if (n > Integer.MAX_VALUE) { throw new IOException("can't process blob larger than Integer.MAX_VALUE"); } byte[] tab = blob.getBytes(1, (int) n); blob.free(); return tab; } break; } /** * The JDBC type CLOB represents the SQL3 type CLOB (Character Large Object). * * <p>A JDBC CLOB value is mapped to an instance of the Clob interface in the Java * programming language. If a driver follows the standard implementation, a Clob object * logically points to the CLOB value on the server rather than containing its character * data, greatly improving efficiency. Two of the methods on the Clob interface materialize * the data of a CLOB object on the client. */ case Types.CLOB: { Clob clob = result.getClob(i); if (clob != null) { long n = clob.length(); if (n > Integer.MAX_VALUE) { throw new IOException("can't process clob larger than Integer.MAX_VALUE"); } String str = clob.getSubString(1, (int) n); clob.free(); return str; } break; } case Types.NCLOB: { NClob nclob = result.getNClob(i); if (nclob != null) { long n = nclob.length(); if (n > Integer.MAX_VALUE) { throw new IOException("can't process nclob larger than Integer.MAX_VALUE"); } String str = nclob.getSubString(1, (int) n); nclob.free(); return str; } break; } /** * The JDBC type DATALINK, new in the JDBC 3.0 API, is a column value that references a file * that is outside of a data source but is managed by the data source. It maps to the Java * type java.net.URL and provides a way to manage external files. For instance, if the data * source is a DBMS, the concurrency controls it enforces on its own data can be applied to * the external file as well. * * <p>A DATALINK value is retrieved from a ResultSet object with the ResultSet methods * getURL or getObject. If the Java platform does not support the type of URL returned by * getURL or getObject, a DATALINK value can be retrieved as a String object with the method * getString. * * <p>java.net.URL values are stored in a database using the method setURL. If the Java * platform does not support the type of URL being set, the method setString can be used * instead. */ case Types.DATALINK: { return result.getURL(i); } /** * The JDBC DATE type represents a date consisting of day, month, and year. The * corresponding SQL DATE type is defined in SQL-92, but it is implemented by only a subset * of the major databases. Some databases offer alternative SQL types that support similar * semantics. */ case Types.DATE: { try { Date d = result.getDate(i, calendar); return d != null ? formatDate(d.getTime()) : null; } catch (SQLException e) { return null; } } case Types.TIME: { try { Time t = result.getTime(i, calendar); return t != null ? formatDate(t.getTime()) : null; } catch (SQLException e) { return null; } } case Types.TIMESTAMP: { try { Timestamp t = result.getTimestamp(i, calendar); return t != null ? formatDate(t.getTime()) : null; } catch (SQLException e) { // java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column ... to // TIMESTAMP. return null; } } /** * The JDBC types DECIMAL and NUMERIC are very similar. They both represent fixed-precision * decimal values. * * <p>The corresponding SQL types DECIMAL and NUMERIC are defined in SQL-92 and are very * widely implemented. These SQL types take precision and scale parameters. The precision is * the total number of decimal digits supported, and the scale is the number of decimal * digits after the decimal point. For most DBMSs, the scale is less than or equal to the * precision. So for example, the value "12.345" has a precision of 5 and a scale of 3, and * the value ".11" has a precision of 2 and a scale of 2. JDBC requires that all DECIMAL and * NUMERIC types support both a precision and a scale of at least 15. * * <p>The sole distinction between DECIMAL and NUMERIC is that the SQL-92 specification * requires that NUMERIC types be represented with exactly the specified precision, whereas * for DECIMAL types, it allows an implementation to add additional precision beyond that * specified when the type was created. Thus a column created with type NUMERIC(12,4) will * always be represented with exactly 12 digits, whereas a column created with type * DECIMAL(12,4) might be represented by some larger number of digits. * * <p>The recommended Java mapping for the DECIMAL and NUMERIC types is * java.math.BigDecimal. The java.math.BigDecimal type provides math operations to allow * BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal * types, with integer types, and with floating point types. * * <p>The method recommended for retrieving DECIMAL and NUMERIC values is * ResultSet.getBigDecimal. JDBC also allows access to these SQL types as simple Strings or * arrays of char. Thus, Java programmers can use getString to receive a DECIMAL or NUMERIC * result. However, this makes the common case where DECIMAL or NUMERIC are used for * currency values rather awkward, since it means that application writers have to perform * math on strings. It is also possible to retrieve these SQL types as any of the Java * numeric types. */ case Types.DECIMAL: case Types.NUMERIC: { BigDecimal bd = null; try { // getBigDecimal() should get obsolete. Most seem to use getString/getObject anyway... bd = result.getBigDecimal(i); } catch (NullPointerException e) { // But is it true? JDBC NPE exists since 13 years? // http://forums.codeguru.com/archive/index.php/t-32443.html // Null values are driving us nuts in JDBC: // http://stackoverflow.com/questions/2777214/when-accessing-resultsets-in-jdbc-is-there-an-elegant-way-to-distinguish-betwee } if (bd == null || result.wasNull()) { return null; } int scale = 2; if (scale >= 0) { bd = bd.setScale(scale, BigDecimal.ROUND_UP); try { long l = bd.longValueExact(); if (Long.toString(l).equals(result.getString(i))) { // convert to long if possible return l; } else { // convert to double (with precision loss) return bd.doubleValue(); } } catch (ArithmeticException e) { return bd.doubleValue(); } } else { return bd.toPlainString(); } } /** * The JDBC type DOUBLE represents a "double precision" floating point number that supports * 15 digits of mantissa. * * <p>The corresponding SQL type is DOUBLE PRECISION, which is defined in SQL-92 and is * widely supported by the major databases. The SQL-92 standard leaves the precision of * DOUBLE PRECISION up to the implementation, but in practice all the major databases * supporting DOUBLE PRECISION support a mantissa precision of at least 15 digits. * * <p>The recommended Java mapping for the DOUBLE type is as a Java double. */ case Types.DOUBLE: { String s = result.getString(i); if (result.wasNull() || s == null) { return null; } NumberFormat format = NumberFormat.getInstance(locale); Number number = format.parse(s); return number.doubleValue(); } /** * The JDBC type FLOAT is basically equivalent to the JDBC type DOUBLE. We provided both * FLOAT and DOUBLE in a possibly misguided attempt at consistency with previous database * APIs. FLOAT represents a "double precision" floating point number that supports 15 digits * of mantissa. * * <p>The corresponding SQL type FLOAT is defined in SQL-92. The SQL-92 standard leaves the * precision of FLOAT up to the implementation, but in practice all the major databases * supporting FLOAT support a mantissa precision of at least 15 digits. * * <p>The recommended Java mapping for the FLOAT type is as a Java double. However, because * of the potential confusion between the double precision SQL FLOAT and the single * precision Java float, we recommend that JDBC programmers should normally use the JDBC * DOUBLE type in preference to FLOAT. */ case Types.FLOAT: { String s = result.getString(i); if (result.wasNull() || s == null) { return null; } NumberFormat format = NumberFormat.getInstance(locale); Number number = format.parse(s); return number.doubleValue(); } /** * The JDBC type JAVA_OBJECT, added in the JDBC 2.0 core API, makes it easier to use objects * in the Java programming language as values in a database. JAVA_OBJECT is simply a type * code for an instance of a class defined in the Java programming language that is stored * as a database object. The type JAVA_OBJECT is used by a database whose type system has * been extended so that it can store Java objects directly. The JAVA_OBJECT value may be * stored as a serialized Java object, or it may be stored in some vendor-specific format. * * <p>The type JAVA_OBJECT is one of the possible values for the column DATA_TYPE in the * ResultSet objects returned by various DatabaseMetaData methods, including getTypeInfo, * getColumns, and getUDTs. The method getUDTs, part of the new JDBC 2.0 core API, will * return information about the Java objects contained in a particular schema when it is * given the appropriate parameters. Having this information available facilitates using a * Java class as a database type. */ case Types.OTHER: case Types.JAVA_OBJECT: { return result.getObject(i); } /** * The JDBC type REAL represents a "single precision" floating point number that supports * seven digits of mantissa. * * <p>The corresponding SQL type REAL is defined in SQL-92 and is widely, though not * universally, supported by the major databases. The SQL-92 standard leaves the precision * of REAL up to the implementation, but in practice all the major databases supporting REAL * support a mantissa precision of at least seven digits. * * <p>The recommended Java mapping for the REAL type is as a Java float. */ case Types.REAL: { String s = result.getString(i); if (result.wasNull() || s == null) { return null; } NumberFormat format = NumberFormat.getInstance(locale); Number number = format.parse(s); return number.doubleValue(); } /** * The JDBC type TINYINT represents an 8-bit integer value between 0 and 255 that may be * signed or unsigned. * * <p>The corresponding SQL type, TINYINT, is currently supported by only a subset of the * major databases. Portable code may therefore prefer to use the JDBC SMALLINT type, which * is widely supported. * * <p>The recommended Java mapping for the JDBC TINYINT type is as either a Java byte or a * Java short. The 8-bit Java byte type represents a signed value from -128 to 127, so it * may not always be appropriate for larger TINYINT values, whereas the 16-bit Java short * will always be able to hold all TINYINT values. */ /** * The JDBC type SMALLINT represents a 16-bit signed integer value between -32768 and 32767. * * <p>The corresponding SQL type, SMALLINT, is defined in SQL-92 and is supported by all the * major databases. The SQL-92 standard leaves the precision of SMALLINT up to the * implementation, but in practice, all the major databases support at least 16 bits. * * <p>The recommended Java mapping for the JDBC SMALLINT type is as a Java short. */ /** * The JDBC type INTEGER represents a 32-bit signed integer value ranging between * -2147483648 and 2147483647. * * <p>The corresponding SQL type, INTEGER, is defined in SQL-92 and is widely supported by * all the major databases. The SQL-92 standard leaves the precision of INTEGER up to the * implementation, but in practice all the major databases support at least 32 bits. * * <p>The recommended Java mapping for the INTEGER type is as a Java int. */ case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: { try { Integer integer = result.getInt(i); return result.wasNull() ? null : integer; } catch (SQLDataException e) { Long l = result.getLong(i); return result.wasNull() ? null : l; } } case Types.SQLXML: { SQLXML xml = result.getSQLXML(i); return xml != null ? xml.getString() : null; } case Types.NULL: { return null; } /** * The JDBC type DISTINCT field (Types class)>DISTINCT represents the SQL3 type DISTINCT. * * <p>The standard mapping for a DISTINCT type is to the Java type to which the base type of * a DISTINCT object would be mapped. For example, a DISTINCT type based on a CHAR would be * mapped to a String object, and a DISTINCT type based on an SQL INTEGER would be mapped to * an int. * * <p>The DISTINCT type may optionally have a custom mapping to a class in the Java * programming language. A custom mapping consists of a class that implements the interface * SQLData and an entry in a java.util.Map object. */ case Types.DISTINCT: { logger.warn("JDBC type not implemented: {}", type); return null; } /** * The JDBC type STRUCT represents the SQL99 structured type. An SQL structured type, which * is defined by a user with a CREATE TYPE statement, consists of one or more attributes. * These attributes may be any SQL data type, built-in or user-defined. * * <p>The standard mapping for the SQL type STRUCT is to a Struct object in the Java * programming language. A Struct object contains a value for each attribute of the STRUCT * value it represents. * * <p>A STRUCT value may optionally be custom mapped to a class in the Java programming * language, and each attribute in the STRUCT may be mapped to a field in the class. A * custom mapping consists of a class that implements the interface SQLData and an entry in * a java.util.Map object. */ case Types.STRUCT: { logger.warn("JDBC type not implemented: {}", type); return null; } case Types.REF: { logger.warn("JDBC type not implemented: {}", type); return null; } case Types.ROWID: { logger.warn("JDBC type not implemented: {}", type); return null; } default: { logger.warn("unknown JDBC type ignored: {}", type); return null; } } return null; }
/** * Makes a database query to convert a table into a set of instances * * @param query the query to convert to instances * @return the instances contained in the result of the query, NULL if the SQL query doesn't * return a ResultSet, e.g., DELETE/INSERT/UPDATE * @throws Exception if an error occurs */ public Instances retrieveInstances(String query) throws Exception { if (m_Debug) System.err.println("Executing query: " + query); connectToDatabase(); if (execute(query) == false) { if (m_PreparedStatement.getUpdateCount() == -1) { throw new Exception("Query didn't produce results"); } else { if (m_Debug) System.err.println(m_PreparedStatement.getUpdateCount() + " rows affected."); close(); return null; } } ResultSet rs = getResultSet(); if (m_Debug) System.err.println("Getting metadata..."); ResultSetMetaData md = rs.getMetaData(); if (m_Debug) System.err.println("Completed getting metadata..."); // Determine structure of the instances int numAttributes = md.getColumnCount(); int[] attributeTypes = new int[numAttributes]; Hashtable[] nominalIndexes = new Hashtable[numAttributes]; FastVector[] nominalStrings = new FastVector[numAttributes]; for (int i = 1; i <= numAttributes; i++) { /* switch (md.getColumnType(i)) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY:*/ switch (translateDBColumnType(md.getColumnTypeName(i))) { case STRING: // System.err.println("String --> nominal"); attributeTypes[i - 1] = Attribute.NOMINAL; nominalIndexes[i - 1] = new Hashtable(); nominalStrings[i - 1] = new FastVector(); break; case TEXT: // System.err.println("Text --> string"); attributeTypes[i - 1] = Attribute.STRING; nominalIndexes[i - 1] = new Hashtable(); nominalStrings[i - 1] = new FastVector(); break; case BOOL: // System.err.println("boolean --> nominal"); attributeTypes[i - 1] = Attribute.NOMINAL; nominalIndexes[i - 1] = new Hashtable(); nominalIndexes[i - 1].put("false", new Double(0)); nominalIndexes[i - 1].put("true", new Double(1)); nominalStrings[i - 1] = new FastVector(); nominalStrings[i - 1].addElement("false"); nominalStrings[i - 1].addElement("true"); break; case DOUBLE: // System.err.println("BigDecimal --> numeric"); attributeTypes[i - 1] = Attribute.NUMERIC; break; case BYTE: // System.err.println("byte --> numeric"); attributeTypes[i - 1] = Attribute.NUMERIC; break; case SHORT: // System.err.println("short --> numeric"); attributeTypes[i - 1] = Attribute.NUMERIC; break; case INTEGER: // System.err.println("int --> numeric"); attributeTypes[i - 1] = Attribute.NUMERIC; break; case LONG: // System.err.println("long --> numeric"); attributeTypes[i - 1] = Attribute.NUMERIC; break; case FLOAT: // System.err.println("float --> numeric"); attributeTypes[i - 1] = Attribute.NUMERIC; break; case DATE: attributeTypes[i - 1] = Attribute.DATE; break; case TIME: attributeTypes[i - 1] = Attribute.DATE; break; default: // System.err.println("Unknown column type"); attributeTypes[i - 1] = Attribute.STRING; } } // For sqlite // cache column names because the last while(rs.next()) { iteration for // the tuples below will close the md object: Vector<String> columnNames = new Vector<String>(); for (int i = 0; i < numAttributes; i++) { columnNames.add(md.getColumnName(i + 1)); } // Step through the tuples if (m_Debug) System.err.println("Creating instances..."); FastVector instances = new FastVector(); int rowCount = 0; while (rs.next()) { if (rowCount % 100 == 0) { if (m_Debug) { System.err.print("read " + rowCount + " instances \r"); System.err.flush(); } } double[] vals = new double[numAttributes]; for (int i = 1; i <= numAttributes; i++) { /*switch (md.getColumnType(i)) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY:*/ switch (translateDBColumnType(md.getColumnTypeName(i))) { case STRING: String str = rs.getString(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { Double index = (Double) nominalIndexes[i - 1].get(str); if (index == null) { index = new Double(nominalStrings[i - 1].size()); nominalIndexes[i - 1].put(str, index); nominalStrings[i - 1].addElement(str); } vals[i - 1] = index.doubleValue(); } break; case TEXT: String txt = rs.getString(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { Double index = (Double) nominalIndexes[i - 1].get(txt); if (index == null) { index = new Double(nominalStrings[i - 1].size()); nominalIndexes[i - 1].put(txt, index); nominalStrings[i - 1].addElement(txt); } vals[i - 1] = index.doubleValue(); } break; case BOOL: boolean boo = rs.getBoolean(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { vals[i - 1] = (boo ? 1.0 : 0.0); } break; case DOUBLE: // BigDecimal bd = rs.getBigDecimal(i, 4); double dd = rs.getDouble(i); // Use the column precision instead of 4? if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { // newInst.setValue(i - 1, bd.doubleValue()); vals[i - 1] = dd; } break; case BYTE: byte by = rs.getByte(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { vals[i - 1] = (double) by; } break; case SHORT: short sh = rs.getShort(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { vals[i - 1] = (double) sh; } break; case INTEGER: int in = rs.getInt(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { vals[i - 1] = (double) in; } break; case LONG: long lo = rs.getLong(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { vals[i - 1] = (double) lo; } break; case FLOAT: float fl = rs.getFloat(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { vals[i - 1] = (double) fl; } break; case DATE: Date date = rs.getDate(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { // TODO: Do a value check here. vals[i - 1] = (double) date.getTime(); } break; case TIME: Time time = rs.getTime(i); if (rs.wasNull()) { vals[i - 1] = Instance.missingValue(); } else { // TODO: Do a value check here. vals[i - 1] = (double) time.getTime(); } break; default: vals[i - 1] = Instance.missingValue(); } } Instance newInst; if (m_CreateSparseData) { newInst = new SparseInstance(1.0, vals); } else { newInst = new Instance(1.0, vals); } instances.addElement(newInst); rowCount++; } // disconnectFromDatabase(); (perhaps other queries might be made) // Create the header and add the instances to the dataset if (m_Debug) System.err.println("Creating header..."); FastVector attribInfo = new FastVector(); for (int i = 0; i < numAttributes; i++) { /* Fix for databases that uppercase column names */ // String attribName = attributeCaseFix(md.getColumnName(i + 1)); String attribName = attributeCaseFix(columnNames.get(i)); switch (attributeTypes[i]) { case Attribute.NOMINAL: attribInfo.addElement(new Attribute(attribName, nominalStrings[i])); break; case Attribute.NUMERIC: attribInfo.addElement(new Attribute(attribName)); break; case Attribute.STRING: Attribute att = new Attribute(attribName, (FastVector) null); attribInfo.addElement(att); for (int n = 0; n < nominalStrings[i].size(); n++) { att.addStringValue((String) nominalStrings[i].elementAt(n)); } break; case Attribute.DATE: attribInfo.addElement(new Attribute(attribName, (String) null)); break; default: throw new Exception("Unknown attribute type"); } } Instances result = new Instances("QueryResult", attribInfo, instances.size()); for (int i = 0; i < instances.size(); i++) { result.add((Instance) instances.elementAt(i)); } close(rs); return result; }
private void testDatetime() throws SQLException { trace("Test DATETIME"); ResultSet rs; Object o; rs = stat.executeQuery("call date '99999-12-23'"); rs.next(); assertEquals("99999-12-23", rs.getString(1)); rs = stat.executeQuery("call timestamp '99999-12-23 01:02:03.000'"); rs.next(); assertEquals("99999-12-23 01:02:03.0", rs.getString(1)); rs = stat.executeQuery("call date '-99999-12-23'"); rs.next(); assertEquals("-99999-12-23", rs.getString(1)); rs = stat.executeQuery("call timestamp '-99999-12-23 01:02:03.000'"); rs.next(); assertEquals("-99999-12-23 01:02:03.0", rs.getString(1)); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY,VALUE DATETIME)"); stat.execute("INSERT INTO TEST VALUES(1,DATE '2011-11-11')"); stat.execute("INSERT INTO TEST VALUES(2,TIMESTAMP '2002-02-02 02:02:02')"); stat.execute("INSERT INTO TEST VALUES(3,TIMESTAMP '1800-1-1 0:0:0')"); stat.execute("INSERT INTO TEST VALUES(4,TIMESTAMP '9999-12-31 23:59:59')"); stat.execute("INSERT INTO TEST VALUES(5,NULL)"); rs = stat.executeQuery( "SELECT 0 ID, " + "TIMESTAMP '9999-12-31 23:59:59' VALUE FROM TEST ORDER BY ID"); assertResultSetMeta( rs, 2, new String[] {"ID", "VALUE"}, new int[] {Types.INTEGER, Types.TIMESTAMP}, new int[] {10, 23}, new int[] {0, 10}); rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID"); assertResultSetMeta( rs, 2, new String[] {"ID", "VALUE"}, new int[] {Types.INTEGER, Types.TIMESTAMP}, new int[] {10, 23}, new int[] {0, 10}); rs.next(); java.sql.Date date; java.sql.Time time; java.sql.Timestamp ts; date = rs.getDate(2); assertTrue(!rs.wasNull()); time = rs.getTime(2); assertTrue(!rs.wasNull()); ts = rs.getTimestamp(2); assertTrue(!rs.wasNull()); trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString()); trace( "Date ms: " + date.getTime() + " Time ms:" + time.getTime() + " Timestamp ms:" + ts.getTime()); trace("1970 ms: " + java.sql.Timestamp.valueOf("1970-01-01 00:00:00.0").getTime()); assertEquals(java.sql.Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), date.getTime()); assertEquals(java.sql.Timestamp.valueOf("1970-01-01 00:00:00.0").getTime(), time.getTime()); assertEquals(java.sql.Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), ts.getTime()); assertTrue(date.equals(java.sql.Date.valueOf("2011-11-11"))); assertTrue(time.equals(java.sql.Time.valueOf("00:00:00"))); assertTrue(ts.equals(java.sql.Timestamp.valueOf("2011-11-11 00:00:00.0"))); assertFalse(rs.wasNull()); o = rs.getObject(2); trace(o.getClass().getName()); assertTrue(o instanceof java.sql.Timestamp); assertTrue( ((java.sql.Timestamp) o).equals(java.sql.Timestamp.valueOf("2011-11-11 00:00:00.0"))); assertFalse(rs.wasNull()); rs.next(); date = rs.getDate("VALUE"); assertTrue(!rs.wasNull()); time = rs.getTime("VALUE"); assertTrue(!rs.wasNull()); ts = rs.getTimestamp("VALUE"); assertTrue(!rs.wasNull()); trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString()); assertEquals("2002-02-02", date.toString()); assertEquals("02:02:02", time.toString()); assertEquals("2002-02-02 02:02:02.0", ts.toString()); rs.next(); assertEquals("1800-01-01", rs.getDate("value").toString()); assertEquals("00:00:00", rs.getTime("value").toString()); assertEquals("1800-01-01 00:00:00.0", rs.getTimestamp("value").toString()); rs.next(); assertEquals("9999-12-31", rs.getDate("Value").toString()); assertEquals("23:59:59", rs.getTime("Value").toString()); assertEquals("9999-12-31 23:59:59.0", rs.getTimestamp("Value").toString()); rs.next(); assertTrue(rs.getDate("Value") == null && rs.wasNull()); assertTrue(rs.getTime("vALUe") == null && rs.wasNull()); assertTrue(rs.getTimestamp(2) == null && rs.wasNull()); assertTrue(!rs.next()); rs = stat.executeQuery( "SELECT DATE '2001-02-03' D, " + "TIME '14:15:16', " + "TIMESTAMP '2007-08-09 10:11:12.141516171' TS FROM TEST"); rs.next(); date = (Date) rs.getObject(1); time = (Time) rs.getObject(2); ts = (Timestamp) rs.getObject(3); assertEquals("2001-02-03", date.toString()); assertEquals("14:15:16", time.toString()); assertEquals("2007-08-09 10:11:12.141516171", ts.toString()); stat.execute("DROP TABLE TEST"); }
@Test public void testJDateTime2Timestamp() { JDateTime jdt = new JDateTime(time); Time sqltime = sqlTimeConverter.convert(jdt); assertEquals(time, sqltime.getTime()); }
public Object orToMysqlType(Column column) throws Exception { if (column instanceof BitColumn) { // This is in byte order BitColumn byteColumn = (BitColumn) column; byte[] byteArray = byteColumn.getValue(); return new String(byteArray); } else if (column instanceof BlobColumn) { BlobColumn blobColumn = (BlobColumn) column; byte[] byteArray = blobColumn.getValue(); return new String(byteArray); } else if (column instanceof DateColumn) { DateColumn dateColumn = (DateColumn) column; Date date = dateColumn.getValue(); return new java.sql.Date(date.getTime()); } else if (column instanceof DatetimeColumn) { DatetimeColumn dateTimeColumn = (DatetimeColumn) column; Date date = dateTimeColumn.getValue(); /** * Bug in OR for DateTIme and Time data-types. MilliSeconds is not available for these columns * but is set with currentMillis() wrongly. */ return new java.sql.Timestamp((date.getTime() / 1000) * 1000); } else if (column instanceof DecimalColumn) { DecimalColumn decimalColumn = (DecimalColumn) column; return decimalColumn.getValue(); } else if (column instanceof DoubleColumn) { DoubleColumn doubleColumn = (DoubleColumn) column; return doubleColumn.getValue(); } else if (column instanceof EnumColumn) { EnumColumn enumColumn = (EnumColumn) column; return enumColumn.getValue(); } else if (column instanceof FloatColumn) { FloatColumn floatColumn = (FloatColumn) column; return floatColumn.getValue(); } else if (column instanceof Int24Column) { Int24Column intColumn = (Int24Column) column; return intColumn.getValue(); } else if (column instanceof LongColumn) { LongColumn longColumn = (LongColumn) column; return longColumn.getValue(); } else if (column instanceof LongLongColumn) { LongLongColumn longLongColumn = (LongLongColumn) column; return longLongColumn.getValue(); } else if (column instanceof NullColumn) { return null; } else if (column instanceof SetColumn) { SetColumn setColumn = (SetColumn) column; return setColumn.getValue(); } else if (column instanceof ShortColumn) { ShortColumn shortColumn = (ShortColumn) column; return shortColumn.getValue(); } else if (column instanceof StringColumn) { StringColumn stringColumn = (StringColumn) column; return new String(stringColumn.getValue(), Charset.defaultCharset()); } else if (column instanceof TimeColumn) { TimeColumn timeColumn = (TimeColumn) column; Time time = timeColumn.getValue(); /** * There is a bug in OR where instead of using the default year as 1970, it is using 0070. * This is a temporary measure to resolve it by working around at this layer. The value * obtained from OR is subtracted from "0070-00-01 00:00:00" */ Calendar c = Calendar.getInstance(); c.set(70, 0, 1, 0, 0, 0); /** * round off the milli-seconds as TimeColumn type has only seconds granularity but Calendar * implementation includes milli-second (System.currentTimeMillis() at the time of * instantiation) */ long rawVal = (c.getTimeInMillis() / 1000) * 1000; long val2 = (time.getTime() / 1000) * 1000; return new java.sql.Time(val2 - rawVal); } else if (column instanceof TimestampColumn) { TimestampColumn timeStampColumn = (TimestampColumn) column; return timeStampColumn.getValue(); } else if (column instanceof TinyColumn) { TinyColumn tinyColumn = (TinyColumn) column; return tinyColumn.getValue(); } else if (column instanceof YearColumn) { YearColumn yearColumn = (YearColumn) column; return yearColumn.getValue(); } else { String message = "Unknown MySQL type in the event" + column.getClass() + " Object = " + column; LOGGER.error(message); throw new RuntimeException(message); } }
public long getTimeInMilliseconds() { return time.getTime(); }
/** * Get or create a time value for the given time. * * @param time the time * @return the value */ public static ValueTime get(Time time) { return fromNanos(DateTimeUtils.nanosFromDate(time.getTime())); }
public void increment(long milliseconds) { time = new Time(time.getTime() + milliseconds); }