Example usage for java.sql PreparedStatement setTime

List of usage examples for java.sql PreparedStatement setTime

Introduction

In this page you can find the example usage for java.sql PreparedStatement setTime.

Prototype

void setTime(int parameterIndex, java.sql.Time x, Calendar cal) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.sql.Time value, using the given Calendar object.

Usage

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDateTimeTimestampWithCalendar() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("create table ts(x timestamp primary key)");
    stat.execute("create table t(x time primary key)");
    stat.execute("create table d(x date)");
    Calendar utcCalendar = new GregorianCalendar(new SimpleTimeZone(0, "Z"));
    TimeZone old = TimeZone.getDefault();
    DateTimeUtils.resetCalendar();//from w ww. j av  a2 s  .c  o  m
    TimeZone.setDefault(TimeZone.getTimeZone("PST"));
    try {
        Timestamp ts1 = Timestamp.valueOf("2010-03-13 18:15:00");
        Time t1 = new Time(ts1.getTime());
        Date d1 = new Date(ts1.getTime());
        // when converted to UTC, this is 03:15, which doesn't actually exist
        // because of summer time change at that day
        Timestamp ts2 = Timestamp.valueOf("2010-03-13 19:15:00");
        Time t2 = new Time(ts2.getTime());
        Date d2 = new Date(ts2.getTime());
        PreparedStatement prep;
        ResultSet rs;
        prep = conn.prepareStatement("insert into ts values(?)");
        prep.setTimestamp(1, ts1, utcCalendar);
        prep.execute();
        prep.setTimestamp(1, ts2, utcCalendar);
        prep.execute();
        prep = conn.prepareStatement("insert into t values(?)");
        prep.setTime(1, t1, utcCalendar);
        prep.execute();
        prep.setTime(1, t2, utcCalendar);
        prep.execute();
        prep = conn.prepareStatement("insert into d values(?)");
        prep.setDate(1, d1, utcCalendar);
        prep.execute();
        prep.setDate(1, d2, utcCalendar);
        prep.execute();
        rs = stat.executeQuery("select * from ts order by x");
        rs.next();
        assertEquals("2010-03-14 02:15:00.0", rs.getString(1));
        assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp(1, utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString());
        assertEquals("2010-03-14 02:15:00.0", rs.getString("x"));
        assertEquals("2010-03-13 18:15:00.0", rs.getTimestamp("x", utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString());
        rs.next();
        assertEquals("2010-03-14 03:15:00.0", rs.getString(1));
        assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp(1, utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp(1).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getString("x"));
        assertEquals("2010-03-13 19:15:00.0", rs.getTimestamp("x", utcCalendar).toString());
        assertEquals("2010-03-14 03:15:00.0", rs.getTimestamp("x").toString());
        rs = stat.executeQuery("select * from t order by x");
        rs.next();
        assertEquals("02:15:00", rs.getString(1));
        assertEquals("18:15:00", rs.getTime(1, utcCalendar).toString());
        assertEquals("02:15:00", rs.getTime(1).toString());
        assertEquals("02:15:00", rs.getString("x"));
        assertEquals("18:15:00", rs.getTime("x", utcCalendar).toString());
        assertEquals("02:15:00", rs.getTime("x").toString());
        rs.next();
        assertEquals("03:15:00", rs.getString(1));
        assertEquals("19:15:00", rs.getTime(1, utcCalendar).toString());
        assertEquals("03:15:00", rs.getTime(1).toString());
        assertEquals("03:15:00", rs.getString("x"));
        assertEquals("19:15:00", rs.getTime("x", utcCalendar).toString());
        assertEquals("03:15:00", rs.getTime("x").toString());
        rs = stat.executeQuery("select * from d order by x");
        rs.next();
        assertEquals("2010-03-14", rs.getString(1));
        assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate(1).toString());
        assertEquals("2010-03-14", rs.getString("x"));
        assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate("x").toString());
        rs.next();
        assertEquals("2010-03-14", rs.getString(1));
        assertEquals("2010-03-13", rs.getDate(1, utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate(1).toString());
        assertEquals("2010-03-14", rs.getString("x"));
        assertEquals("2010-03-13", rs.getDate("x", utcCalendar).toString());
        assertEquals("2010-03-14", rs.getDate("x").toString());
    } finally {
        TimeZone.setDefault(old);
        DateTimeUtils.resetCalendar();
    }
    stat.execute("drop table ts");
    stat.execute("drop table t");
    stat.execute("drop table d");
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testDatetimeWithCalendar() throws SQLException {
    trace("test DATETIME with Calendar");
    ResultSet rs;//from  ww w. j  a  v a 2  s.  com

    stat = conn.createStatement();
    stat.execute("CREATE TABLE test(ID INT PRIMARY KEY, D DATE, T TIME, TS TIMESTAMP)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO test VALUES(?, ?, ?, ?)");
    Calendar regular = Calendar.getInstance();
    Calendar other = null;
    // search a locale that has a _different_ raw offset
    long testTime = java.sql.Date.valueOf("2001-02-03").getTime();
    for (String s : TimeZone.getAvailableIDs()) {
        TimeZone zone = TimeZone.getTimeZone(s);
        long rawOffsetDiff = regular.getTimeZone().getRawOffset() - zone.getRawOffset();
        // must not be the same timezone (not 0 h and not 24 h difference
        // as for Pacific/Auckland and Etc/GMT+12)
        if (rawOffsetDiff != 0 && rawOffsetDiff != 1000 * 60 * 60 * 24) {
            if (regular.getTimeZone().getOffset(testTime) != zone.getOffset(testTime)) {
                other = Calendar.getInstance(zone);
                break;
            }
        }
    }

    trace("regular offset = " + regular.getTimeZone().getRawOffset() + " other = "
            + other.getTimeZone().getRawOffset());

    prep.setInt(1, 0);
    prep.setDate(2, null, regular);
    prep.setTime(3, null, regular);
    prep.setTimestamp(4, null, regular);
    prep.execute();

    prep.setInt(1, 1);
    prep.setDate(2, null, other);
    prep.setTime(3, null, other);
    prep.setTimestamp(4, null, other);
    prep.execute();

    prep.setInt(1, 2);
    prep.setDate(2, java.sql.Date.valueOf("2001-02-03"), regular);
    prep.setTime(3, java.sql.Time.valueOf("04:05:06"), regular);
    prep.setTimestamp(4, Timestamp.valueOf("2007-08-09 10:11:12.131415"), regular);
    prep.execute();

    prep.setInt(1, 3);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"), other);
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"), other);
    prep.setTimestamp(4, Timestamp.valueOf("2107-08-09 10:11:12.131415"), other);
    prep.execute();

    prep.setInt(1, 4);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"));
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"));
    prep.setTimestamp(4, Timestamp.valueOf("2107-08-09 10:11:12.131415"));
    prep.execute();

    rs = stat.executeQuery("SELECT * FROM test ORDER BY ID");
    assertResultSetMeta(rs, 4, new String[] { "ID", "D", "T", "TS" },
            new int[] { Types.INTEGER, Types.DATE, Types.TIME, Types.TIMESTAMP }, new int[] { 10, 8, 6, 23 },
            new int[] { 0, 0, 0, 10 });

    rs.next();
    assertEquals(0, rs.getInt(1));
    assertTrue(rs.getDate(2, regular) == null && rs.wasNull());
    assertTrue(rs.getTime(3, regular) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, regular) == null && rs.wasNull());

    rs.next();
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getDate(2, other) == null && rs.wasNull());
    assertTrue(rs.getTime(3, other) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, other) == null && rs.wasNull());

    rs.next();
    assertEquals(2, rs.getInt(1));
    assertEquals("2001-02-03", rs.getDate(2, regular).toString());
    assertEquals("04:05:06", rs.getTime(3, regular).toString());
    assertFalse(rs.getTime(3, other).toString().equals("04:05:06"));
    assertEquals("2007-08-09 10:11:12.131415", rs.getTimestamp(4, regular).toString());
    assertFalse(rs.getTimestamp(4, other).toString().equals("2007-08-09 10:11:12.131415"));

    rs.next();
    assertEquals(3, rs.getInt("ID"));
    assertFalse(rs.getTimestamp("TS", regular).toString().equals("2107-08-09 10:11:12.131415"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS", other).toString());
    assertFalse(rs.getTime("T", regular).toString().equals("14:05:06"));
    assertEquals("14:05:06", rs.getTime("T", other).toString());
    // checkFalse(rs.getDate(2, regular).toString(), "2101-02-03");
    // check(rs.getDate("D", other).toString(), "2101-02-03");

    rs.next();
    assertEquals(4, rs.getInt("ID"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS").toString());
    assertEquals("14:05:06", rs.getTime("T").toString());
    assertEquals("2101-02-03", rs.getDate("D").toString());

    assertFalse(rs.next());
    stat.execute("DROP TABLE test");
}

From source file:org.castor.jdo.engine.SQLTypeInfos.java

/**
 * Set given value on given PreparedStatement at given index with given SQL type.
 * //from   w w w . j  a  v  a2s .  c om
 * @param stmt The PreparedStatement to set value on.
 * @param index The index of the value in the PreparedStatement.
 * @param value The value to set.
 * @param sqlType The SQL type of the value.
 */
public static void setValue(final PreparedStatement stmt, final int index, final Object value,
        final int sqlType) {
    try {
        if (value == null) {
            stmt.setNull(index, sqlType);
        } else {
            // Special processing for BLOB and CLOB types, because they are mapped
            // by Castor to java.io.InputStream and java.io.Reader, respectively,
            // while JDBC driver expects java.sql.Blob and java.sql.Clob.
            switch (sqlType) {
            case Types.FLOAT:
            case Types.DOUBLE:
                stmt.setDouble(index, ((Double) value).doubleValue());
                break;
            case Types.REAL:
                stmt.setFloat(index, ((Float) value).floatValue());
                break;
            case Types.TIME:
                final Time time = value instanceof java.util.Date ? new Time(((java.util.Date) value).getTime())
                        : null;
                stmt.setTime(index, time != null ? time : (Time) value, getCalendar());
                break;
            case Types.DATE:
                final Date date = value instanceof java.util.Date ? new Date(((java.util.Date) value).getTime())
                        : null;
                stmt.setDate(index, date != null ? date : (Date) value);
                break;
            case Types.TIMESTAMP:
                final Timestamp timestamp = value instanceof java.util.Date
                        ? new Timestamp(((java.util.Date) value).getTime())
                        : null;
                stmt.setTimestamp(index, timestamp != null ? timestamp : (Timestamp) value, getCalendar());
                break;
            case Types.BLOB:
                try {
                    InputStream stream;
                    if (value instanceof byte[]) {
                        stream = new ByteArrayInputStream((byte[]) value);
                    } else {
                        stream = (InputStream) value;
                    }
                    stmt.setBinaryStream(index, stream, stream.available());
                } catch (IOException ex) {
                    throw new SQLException(ex.toString());
                }
                break;
            case Types.CLOB:
                if (value instanceof String) {
                    stmt.setCharacterStream(index, new StringReader((String) value),
                            Math.min(((String) value).length(), Integer.MAX_VALUE));
                } else {
                    stmt.setCharacterStream(index, ((Clob) value).getCharacterStream(),
                            (int) Math.min(((Clob) value).length(), Integer.MAX_VALUE));
                }
                break;
            default:
                stmt.setObject(index, value, sqlType);
                break;
            }
        }
    } catch (SQLException ex) {
        LOG.error("Unexpected SQL exception: ", ex);
    }
}

From source file:org.moqui.impl.entity.EntityJavaUtil.java

public static void setPreparedStatementValue(PreparedStatement ps, int index, Object value, FieldInfo fi,
        boolean useBinaryTypeForBlob, EntityFacade efi) throws EntityException {
    try {//from w ww. java  2 s .  c o m
        // allow setting, and searching for, String values for all types; JDBC driver should handle this okay
        if (value instanceof CharSequence) {
            ps.setString(index, value.toString());
        } else {
            switch (fi.typeValue) {
            case 1:
                if (value != null) {
                    ps.setString(index, value.toString());
                } else {
                    ps.setNull(index, Types.VARCHAR);
                }
                break;
            case 2:
                if (value != null) {
                    Class valClass = value.getClass();
                    if (valClass == Timestamp.class) {
                        ps.setTimestamp(index, (Timestamp) value, efi.getCalendarForTzLc());
                    } else if (valClass == java.sql.Date.class) {
                        ps.setDate(index, (java.sql.Date) value, efi.getCalendarForTzLc());
                    } else if (valClass == java.util.Date.class) {
                        ps.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime()),
                                efi.getCalendarForTzLc());
                    } else {
                        throw new IllegalArgumentException("Class " + valClass.getName()
                                + " not allowed for date-time (Timestamp) fields, for field " + fi.entityName
                                + "." + fi.name);
                    }
                } else {
                    ps.setNull(index, Types.TIMESTAMP);
                }
                break;
            case 3:
                Time tm = (Time) value;
                // logger.warn("=================== setting time tm=${tm} tm long=${tm.getTime()}, cal=${cal}")
                if (value != null) {
                    ps.setTime(index, tm, efi.getCalendarForTzLc());
                } else {
                    ps.setNull(index, Types.TIME);
                }
                break;
            case 4:
                if (value != null) {
                    Class valClass = value.getClass();
                    if (valClass == java.sql.Date.class) {
                        java.sql.Date dt = (java.sql.Date) value;
                        // logger.warn("=================== setting date dt=${dt} dt long=${dt.getTime()}, cal=${cal}")
                        ps.setDate(index, dt, efi.getCalendarForTzLc());
                    } else if (valClass == Timestamp.class) {
                        ps.setDate(index, new java.sql.Date(((Timestamp) value).getTime()),
                                efi.getCalendarForTzLc());
                    } else if (valClass == java.util.Date.class) {
                        ps.setDate(index, new java.sql.Date(((java.util.Date) value).getTime()),
                                efi.getCalendarForTzLc());
                    } else {
                        throw new IllegalArgumentException("Class " + valClass.getName()
                                + " not allowed for date fields, for field " + fi.entityName + "." + fi.name);
                    }
                } else {
                    ps.setNull(index, Types.DATE);
                }
                break;
            case 5:
                if (value != null) {
                    ps.setInt(index, ((Number) value).intValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 6:
                if (value != null) {
                    ps.setLong(index, ((Number) value).longValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 7:
                if (value != null) {
                    ps.setFloat(index, ((Number) value).floatValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 8:
                if (value != null) {
                    ps.setDouble(index, ((Number) value).doubleValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 9:
                if (value != null) {
                    Class valClass = value.getClass();
                    // most common cases BigDecimal, Double, Float; then allow any Number
                    if (valClass == BigDecimal.class) {
                        ps.setBigDecimal(index, (BigDecimal) value);
                    } else if (valClass == Double.class) {
                        ps.setDouble(index, (Double) value);
                    } else if (valClass == Float.class) {
                        ps.setFloat(index, (Float) value);
                    } else if (value instanceof Number) {
                        ps.setDouble(index, ((Number) value).doubleValue());
                    } else {
                        throw new IllegalArgumentException("Class " + valClass.getName()
                                + " not allowed for number-decimal (BigDecimal) fields, for field "
                                + fi.entityName + "." + fi.name);
                    }
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 10:
                if (value != null) {
                    ps.setBoolean(index, (Boolean) value);
                } else {
                    ps.setNull(index, Types.BOOLEAN);
                }
                break;
            case 11:
                if (value != null) {
                    try {
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(os);
                        oos.writeObject(value);
                        oos.close();
                        byte[] buf = os.toByteArray();
                        os.close();

                        ByteArrayInputStream is = new ByteArrayInputStream(buf);
                        ps.setBinaryStream(index, is, buf.length);
                        is.close();
                    } catch (IOException ex) {
                        throw new EntityException(
                                "Error setting serialized object, for field " + fi.entityName + "." + fi.name,
                                ex);
                    }
                } else {
                    if (useBinaryTypeForBlob) {
                        ps.setNull(index, Types.BINARY);
                    } else {
                        ps.setNull(index, Types.BLOB);
                    }
                }
                break;
            case 12:
                if (value instanceof byte[]) {
                    ps.setBytes(index, (byte[]) value);
                    /*
                    } else if (value instanceof ArrayList) {
                        ArrayList valueAl = (ArrayList) value;
                        byte[] theBytes = new byte[valueAl.size()];
                        valueAl.toArray(theBytes);
                        ps.setBytes(index, theBytes);
                    */
                } else if (value instanceof ByteBuffer) {
                    ByteBuffer valueBb = (ByteBuffer) value;
                    ps.setBytes(index, valueBb.array());
                } else if (value instanceof Blob) {
                    Blob valueBlob = (Blob) value;
                    // calling setBytes instead of setBlob
                    // ps.setBlob(index, (Blob) value)
                    // Blob blb = value
                    ps.setBytes(index, valueBlob.getBytes(1, (int) valueBlob.length()));
                } else {
                    if (value != null) {
                        throw new IllegalArgumentException("Type not supported for BLOB field: "
                                + value.getClass().getName() + ", for field " + fi.entityName + "." + fi.name);
                    } else {
                        if (useBinaryTypeForBlob) {
                            ps.setNull(index, Types.BINARY);
                        } else {
                            ps.setNull(index, Types.BLOB);
                        }
                    }
                }
                break;
            case 13:
                if (value != null) {
                    ps.setClob(index, (Clob) value);
                } else {
                    ps.setNull(index, Types.CLOB);
                }
                break;
            case 14:
                if (value != null) {
                    ps.setTimestamp(index, (Timestamp) value);
                } else {
                    ps.setNull(index, Types.TIMESTAMP);
                }
                break;
            // TODO: is this the best way to do collections and such?
            case 15:
                if (value != null) {
                    ps.setObject(index, value, Types.JAVA_OBJECT);
                } else {
                    ps.setNull(index, Types.JAVA_OBJECT);
                }
                break;
            }
        }
    } catch (SQLException sqle) {
        throw new EntityException("SQL Exception while setting value [" + value + "]("
                + (value != null ? value.getClass().getName() : "null") + "), type " + fi.type + ", for field "
                + fi.entityName + "." + fi.name + ": " + sqle.toString(), sqle);
    } catch (Exception e) {
        throw new EntityException(
                "Error while setting value for field " + fi.entityName + "." + fi.name + ": " + e.toString(),
                e);
    }
}