下面列出了java.sql.PreparedStatement#setTime ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testBatch() throws SQLException, MalformedURLException {
PreparedStatement preparedStatement = multiHostConnection.prepareStatement("UPDATE test SET a = ? WHERE b = ?");
preparedStatement.setShort(1, (short) 12);
preparedStatement.setTime(2, new Time(System.currentTimeMillis()));
preparedStatement.addBatch();
int[] resultSet = preparedStatement.executeBatch();
preparedStatement.clearBatch();
verify(mysqlPreparedStatement).executeBatch();
verify(mysqlPreparedStatement).addBatch();
verify(mysqlPreparedStatement).clearBatch();
TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
assertThat(spans.size(), is(1));
assertDBSpan(spans.get(0), "Mysql/JDBI/PreparedStatement/executeBatch", "");
}
@Override
void apply(PreparedStatement stmt, int stmtIndex, DataFrameRow<R, C> row) {
final R rowKey = row.key();
try {
switch (rowKeyType) {
case BIT: stmt.setBoolean(stmtIndex, rowKeyMapper.applyAsBoolean(rowKey)); break;
case BOOLEAN: stmt.setBoolean(stmtIndex, rowKeyMapper.applyAsBoolean(rowKey)); break;
case TINYINT: stmt.setInt(stmtIndex, rowKeyMapper.applyAsInt(rowKey)); break;
case SMALLINT: stmt.setInt(stmtIndex, rowKeyMapper.applyAsInt(rowKey)); break;
case FLOAT: stmt.setDouble(stmtIndex, rowKeyMapper.applyAsDouble(rowKey)); break;
case INTEGER: stmt.setInt(stmtIndex, rowKeyMapper.applyAsInt(rowKey)); break;
case BIGINT: stmt.setLong(stmtIndex, rowKeyMapper.applyAsLong(rowKey)); break;
case DOUBLE: stmt.setDouble(stmtIndex, rowKeyMapper.applyAsDouble(rowKey)); break;
case DECIMAL: stmt.setDouble(stmtIndex, rowKeyMapper.applyAsDouble(rowKey)); break;
case VARCHAR: stmt.setString(stmtIndex, (String)rowKeyMapper.apply(rowKey)); break;
case DATE: stmt.setDate(stmtIndex, (Date)rowKeyMapper.apply(rowKey)); break;
case TIME: stmt.setTime(stmtIndex, (Time)rowKeyMapper.apply(rowKey)); break;
case DATETIME: stmt.setTimestamp(stmtIndex, (Timestamp)rowKeyMapper.apply(rowKey)); break;
default: throw new IllegalStateException("Unsupported column type:" + rowKeyType);
}
} catch (Exception ex) {
throw new DataFrameException("Failed to apply row key to SQL statement at " + rowKey, ex);
}
}
/**
* Binds arguments to prepared statement
* @param stmt the prepared statement reference
* @return the same as arg
* @throws SQLException if binding fails
*/
private PreparedStatement bindArgs(PreparedStatement stmt) throws SQLException {
for (int i=0; i<args.length; ++i) {
final Object value = args[i];
if (value instanceof Boolean) stmt.setBoolean(i+1, (Boolean)value);
else if (value instanceof Short) stmt.setShort(i+1, (Short)value);
else if (value instanceof Integer) stmt.setInt(i+1, (Integer)value);
else if (value instanceof Float) stmt.setFloat(i+1, (Float)value);
else if (value instanceof Long) stmt.setLong(i+1, (Long)value);
else if (value instanceof Double) stmt.setDouble(i+1, (Double)value);
else if (value instanceof String) stmt.setString(i+1, (String)value);
else if (value instanceof java.sql.Date) stmt.setDate(i+1, (java.sql.Date)value);
else if (value instanceof Timestamp) stmt.setTimestamp(i+1, (Timestamp)value);
else if (value instanceof LocalDate) stmt.setDate(i + 1, java.sql.Date.valueOf((LocalDate)value));
else if (value instanceof LocalTime) stmt.setTime(i+1, Time.valueOf((LocalTime)value));
else if (value instanceof LocalDateTime) stmt.setTimestamp(i+1, Timestamp.valueOf((LocalDateTime)value));
else if (value instanceof ZonedDateTime) {
final ZonedDateTime zonedDateTime = (ZonedDateTime)value;
final LocalDateTime dateTime = zonedDateTime.toLocalDateTime();
stmt.setTimestamp(i+1, Timestamp.valueOf(dateTime));
} else {
throw new RuntimeException("Unsupported argument, cannot be bound to SQL statement: " + value);
}
}
return stmt;
}
@Test
public void testSubtractTime() throws Exception {
Connection conn;
PreparedStatement stmt;
ResultSet rs;
String tName = generateUniqueName();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
conn = DriverManager.getConnection(getUrl(), props);
conn.createStatement()
.execute(
"create table " + tName + " (ts time primary key)");
conn.close();
conn = DriverManager.getConnection(getUrl(), props);
stmt = conn.prepareStatement("upsert into " + tName + " values (?)");
Time time = new Time(1995 - 1900, 4, 2);
stmt.setTime(1, time);
stmt.execute();
conn.commit();
conn = DriverManager.getConnection(getUrl(), props);
rs = conn.createStatement().executeQuery("SELECT ts FROM " + tName + "");
assertTrue(rs.next());
assertEquals(time.getTime(),rs.getTimestamp(1).getTime());
conn = DriverManager.getConnection(getUrl(), props);
rs = conn.createStatement().executeQuery("SELECT ts - 1 FROM " + tName);
assertTrue(rs.next());
assertEquals(time.getTime() - MILLIS_IN_DAY,rs.getTimestamp(1).getTime());
}
@Test
public void assertSetTime() throws SQLException {
for (PreparedStatement each : preparedStatements) {
Time now = new Time(0L);
each.setTime(1, now);
each.setTime(2, now, Calendar.getInstance());
assertParameter(each, 1, now);
assertParameter(each, 2, now);
}
}
/** {@inheritDoc} */
@Override public byte[] loadCheckpoint(String key) throws IgniteSpiException {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = getConnection();
st = conn.prepareStatement(selSql);
st.setString(1, key);
st.setTime(2, new Time(U.currentTimeMillis()));
rs = st.executeQuery();
return rs.next() ? rs.getBytes(1) : null;
}
catch (SQLException e) {
throw new IgniteSpiException("Failed to load checkpoint [tblName=" + tblName + ", key=" + key + ']', e);
}
finally {
U.close(rs, log);
U.close(st, log);
U.close(conn, log);
}
}
private void insertData(String tableName, int startIndex, int endIndex) throws SQLException{
Connection connection = TestUtil.getConnection();
PreparedStatement ps = connection.prepareStatement("INSERT INTO " + tableName + "(bigIntegerField, blobField, charField," +
"charForBitData, clobField, dateField, decimalField, doubleField, floatField, longVarcharForBitDataField, numericField," +
"realField, smallIntField, timeField, timestampField, varcharField, varcharForBitData, xmlField) values( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, xmlparse(document cast (? as clob) PRESERVE WHITESPACE))");
for (int i = startIndex; i < endIndex; i++) {
int lessThan10 = i % 10;
ps.setLong(1, i); //BIG INT
ps.setBlob(2,new ByteArrayInputStream(new byte[]{(byte)i,(byte)i,(byte)i,(byte)i}));
ps.setString(3, ""+lessThan10);
ps.setBytes(4, ("" + lessThan10).getBytes());
ps.setClob(5, new StringReader("SOME CLOB " + i));
ps.setDate(6, new Date(System.currentTimeMillis()));
ps.setBigDecimal(7, new BigDecimal(lessThan10 + .8));
ps.setDouble(8, i + .88);
ps.setFloat(9, i + .9f);
ps.setBytes(10, ("A" + lessThan10).getBytes());
ps.setBigDecimal(11, new BigDecimal(i));
ps.setFloat(12, lessThan10 * 1111);
ps.setShort(13, (short)i);
ps.setTime(14, new Time(System.currentTimeMillis()));
ps.setTimestamp(15, new Timestamp(System.currentTimeMillis()));
ps.setString(16, "HI" + lessThan10);
ps.setBytes(17, ("" + lessThan10).getBytes());
ps.setClob(18, new StringReader("<xml><sometag>SOME XML CLOB " + i + "</sometag></xml>"));
ps.execute();
}
}
public static void setField(PreparedStatement upload, int type, Object field, int index) throws SQLException {
if (field == null) {
upload.setNull(index + 1, type);
} else {
try {
// casting values as suggested by http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html
switch (type) {
case java.sql.Types.NULL:
upload.setNull(index + 1, type);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
upload.setBoolean(index + 1, (boolean) field);
break;
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.LONGNVARCHAR:
upload.setString(index + 1, (String) field);
break;
case java.sql.Types.TINYINT:
upload.setByte(index + 1, (byte) field);
break;
case java.sql.Types.SMALLINT:
upload.setShort(index + 1, (short) field);
break;
case java.sql.Types.INTEGER:
upload.setInt(index + 1, (int) field);
break;
case java.sql.Types.BIGINT:
upload.setLong(index + 1, (long) field);
break;
case java.sql.Types.REAL:
upload.setFloat(index + 1, (float) field);
break;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
upload.setDouble(index + 1, (double) field);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.NUMERIC:
upload.setBigDecimal(index + 1, (java.math.BigDecimal) field);
break;
case java.sql.Types.DATE:
upload.setDate(index + 1, (java.sql.Date) field);
break;
case java.sql.Types.TIME:
upload.setTime(index + 1, (java.sql.Time) field);
break;
case java.sql.Types.TIMESTAMP:
upload.setTimestamp(index + 1, (java.sql.Timestamp) field);
break;
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
upload.setBytes(index + 1, (byte[]) field);
break;
default:
upload.setObject(index + 1, field);
LOG.warn("Unmanaged sql type ({}) for column {}. Best effort approach to set its value: {}.",
type, index + 1, field);
// case java.sql.Types.SQLXML
// case java.sql.Types.ARRAY:
// case java.sql.Types.JAVA_OBJECT:
// case java.sql.Types.BLOB:
// case java.sql.Types.CLOB:
// case java.sql.Types.NCLOB:
// case java.sql.Types.DATALINK:
// case java.sql.Types.DISTINCT:
// case java.sql.Types.OTHER:
// case java.sql.Types.REF:
// case java.sql.Types.ROWID:
// case java.sql.Types.STRUC
}
} catch (ClassCastException e) {
// enrich the exception with detailed information.
String errorMessage = String.format(
"%s, field index: %s, field value: %s.", e.getMessage(), index, field);
ClassCastException enrichedException = new ClassCastException(errorMessage);
enrichedException.setStackTrace(e.getStackTrace());
throw enrichedException;
}
}
}
/** Assigns a value to a dynamic parameter in a prepared statement, calling
* the appropriate {@code setXxx} method based on the type of the value. */
private static void setDynamicParam(PreparedStatement preparedStatement,
int i, Object value) throws SQLException {
if (value == null) {
preparedStatement.setObject(i, null, SqlType.ANY.id);
} else if (value instanceof Timestamp) {
preparedStatement.setTimestamp(i, (Timestamp) value);
} else if (value instanceof Time) {
preparedStatement.setTime(i, (Time) value);
} else if (value instanceof String) {
preparedStatement.setString(i, (String) value);
} else if (value instanceof Integer) {
preparedStatement.setInt(i, (Integer) value);
} else if (value instanceof Double) {
preparedStatement.setDouble(i, (Double) value);
} else if (value instanceof java.sql.Array) {
preparedStatement.setArray(i, (java.sql.Array) value);
} else if (value instanceof BigDecimal) {
preparedStatement.setBigDecimal(i, (BigDecimal) value);
} else if (value instanceof Boolean) {
preparedStatement.setBoolean(i, (Boolean) value);
} else if (value instanceof Blob) {
preparedStatement.setBlob(i, (Blob) value);
} else if (value instanceof Byte) {
preparedStatement.setByte(i, (Byte) value);
} else if (value instanceof NClob) {
preparedStatement.setNClob(i, (NClob) value);
} else if (value instanceof Clob) {
preparedStatement.setClob(i, (Clob) value);
} else if (value instanceof byte[]) {
preparedStatement.setBytes(i, (byte[]) value);
} else if (value instanceof Date) {
preparedStatement.setDate(i, (Date) value);
} else if (value instanceof Float) {
preparedStatement.setFloat(i, (Float) value);
} else if (value instanceof Long) {
preparedStatement.setLong(i, (Long) value);
} else if (value instanceof Ref) {
preparedStatement.setRef(i, (Ref) value);
} else if (value instanceof RowId) {
preparedStatement.setRowId(i, (RowId) value);
} else if (value instanceof Short) {
preparedStatement.setShort(i, (Short) value);
} else if (value instanceof URL) {
preparedStatement.setURL(i, (URL) value);
} else if (value instanceof SQLXML) {
preparedStatement.setSQLXML(i, (SQLXML) value);
} else {
preparedStatement.setObject(i, value);
}
}
/** Adding this method to ensure that super class' setInto method doesn't get called
* that leads to the violation of JDBC spec( untyped nulls ) when batching is turned on.
*/
public void setInto(PreparedStatement ps, int position) throws SQLException, StandardException {
ps.setTime(position, getTime((Calendar) null));
}
/**
* Test NULLIF with parameter as first operand
*
* @throws SQLException
*/
public void testParameterForFirstOperandToNullIf() throws SQLException {
for (int secondColumnType = 0; secondColumnType < SQLUtilities.SQLTypes.length; secondColumnType++) {
String nullIfString = new String("SELECT NULLIF(?,"
+ SQLUtilities.allDataTypesColumnNames[secondColumnType]
+ ") from AllDataTypesTable");
int row = 0;
try {
PreparedStatement ps = prepareStatement(nullIfString);
switch (secondColumnType) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
ps.setBoolean(1, true);
break;
case 8: // 'LONG VARCHAR'
case 11: // 'LONG VARCHAR FOR BIT DATA'
case 12: // 'CLOB'
case 16: // 'BLOB'
// Take specific case of LONG VARCHAR. Prepare of
// nullif(?,long varchar)
// fails early on because at bind time, Derby tries to set ?
// to
// long varchar. But comparison between 2 long varchars is
// not
// supported and hence bind code in
// BinaryComparisonOperatorNode fails
// Similar thing happens for CLOB, BLOB and LONG VARCHAR FOR
// BIT DATA
case 9:
case 10:
ps.setBinaryStream(1, (java.io.InputStream) null, 1);
break;
case 13:// DATE
ps.setDate(1, Date.valueOf("2000-01-01"));
break;
case 14:// TIME
ps.setTime(1, Time.valueOf("15:30:20"));
break;
case 15:// TIMESTAMP
ps
.setTimestamp(1, Timestamp
.valueOf("2000-01-01 15:30:20"));
break;
default:
break;
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String val = rs.getString(1);
if (usingDerbyNetClient())
assertEquals(paramResultsClient[secondColumnType][row],
val);
else
assertEquals(paramResults[secondColumnType][row], val);
row++;
}
rs.close();
ps.close();
} catch (SQLException e) {
for (int r = row; r < 4; r++) {
if (usingDerbyNetClient())
assertEquals(paramResultsClient[secondColumnType][row],
"Exception");
else
assertEquals(paramResults[secondColumnType][row],
"Exception");
}
}
}
}
/**
* @param preparedState
* @param param
* @throws SQLException
*/
private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param)
throws SQLException {
boolean isNull = (null == param.getValue());
Class<?> clazz;
try {
clazz = Class.forName(param.getClassName());
} catch (ClassNotFoundException e) {
throw new InternalErrorException(e);
}
Rep rep = Rep.of(clazz);
switch (rep) {
case PRIMITIVE_CHAR:
case CHARACTER:
case STRING:
preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
break;
case PRIMITIVE_INT:
case INTEGER:
preparedState.setInt(index, isNull ? 0 : Integer.parseInt(param.getValue()));
break;
case PRIMITIVE_SHORT:
case SHORT:
preparedState.setShort(index, isNull ? 0 : Short.parseShort(param.getValue()));
break;
case PRIMITIVE_LONG:
case LONG:
preparedState.setLong(index, isNull ? 0 : Long.parseLong(param.getValue()));
break;
case PRIMITIVE_FLOAT:
case FLOAT:
preparedState.setFloat(index, isNull ? 0 : Float.parseFloat(param.getValue()));
break;
case PRIMITIVE_DOUBLE:
case DOUBLE:
preparedState.setDouble(index, isNull ? 0 : Double.parseDouble(param.getValue()));
break;
case PRIMITIVE_BOOLEAN:
case BOOLEAN:
preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue()));
break;
case PRIMITIVE_BYTE:
case BYTE:
preparedState.setByte(index, isNull ? 0 : Byte.parseByte(param.getValue()));
break;
case JAVA_UTIL_DATE:
case JAVA_SQL_DATE:
preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
break;
case JAVA_SQL_TIME:
preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
break;
case JAVA_SQL_TIMESTAMP:
preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
break;
default:
preparedState.setObject(index, isNull ? null : param.getValue());
}
}
/**
* Determines how to map the given value to the appropriate JDBC data jdbcType and sets the parameter on the
* provided PreparedStatement
*
* @param stmt the PreparedStatement to set the parameter on
* @param attrName the name of the attribute that the parameter is coming from - for logging purposes
* @param parameterIndex the index of the HiveQL parameter to set
* @param parameterValue the value of the HiveQL parameter to set
* @param jdbcType the JDBC Type of the HiveQL parameter to set
* @throws SQLException if the PreparedStatement throws a SQLException when calling the appropriate setter
*/
protected void setParameter(final PreparedStatement stmt, final String attrName, final int parameterIndex, final String parameterValue, final int jdbcType) throws SQLException {
if (parameterValue == null) {
stmt.setNull(parameterIndex, jdbcType);
} else {
try {
switch (jdbcType) {
case Types.BIT:
case Types.BOOLEAN:
stmt.setBoolean(parameterIndex, Boolean.parseBoolean(parameterValue));
break;
case Types.TINYINT:
stmt.setByte(parameterIndex, Byte.parseByte(parameterValue));
break;
case Types.SMALLINT:
stmt.setShort(parameterIndex, Short.parseShort(parameterValue));
break;
case Types.INTEGER:
stmt.setInt(parameterIndex, Integer.parseInt(parameterValue));
break;
case Types.BIGINT:
stmt.setLong(parameterIndex, Long.parseLong(parameterValue));
break;
case Types.REAL:
stmt.setFloat(parameterIndex, Float.parseFloat(parameterValue));
break;
case Types.FLOAT:
case Types.DOUBLE:
stmt.setDouble(parameterIndex, Double.parseDouble(parameterValue));
break;
case Types.DECIMAL:
case Types.NUMERIC:
stmt.setBigDecimal(parameterIndex, new BigDecimal(parameterValue));
break;
case Types.DATE:
stmt.setDate(parameterIndex, new Date(Long.parseLong(parameterValue)));
break;
case Types.TIME:
stmt.setTime(parameterIndex, new Time(Long.parseLong(parameterValue)));
break;
case Types.TIMESTAMP:
stmt.setTimestamp(parameterIndex, new Timestamp(Long.parseLong(parameterValue)));
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGNVARCHAR:
case Types.LONGVARCHAR:
stmt.setString(parameterIndex, parameterValue);
break;
default:
stmt.setObject(parameterIndex, parameterValue, jdbcType);
break;
}
} catch (SQLException e) {
// Log which attribute/parameter had an error, then rethrow to be handled at the top level
getLogger().error("Error setting parameter {} to value from {} ({})", new Object[]{parameterIndex, attrName, parameterValue}, e);
throw e;
}
}
}
/** Adding this method to ensure that super class' setInto method doesn't get called
* that leads to the violation of JDBC spec( untyped nulls ) when batching is turned on.
*/
public void setInto(PreparedStatement ps, int position) throws SQLException, StandardException {
ps.setTime(position, getTime((Calendar) null));
}
public void testAllDataTypesDiskWrite() throws SQLException {
EmbedConnection conn = (EmbedConnection)TestUtil.getConnection();
Statement st = conn.createStatement();
try {
st.execute("drop table test");
} catch (Exception i) {
}
try {
st
.execute("create table test (id int primary key, "
+ "lv bigint, si smallint, fl float, dbl double, "
+ "nmr numeric(10,2), dml decimal(30,20), "
+ "dt date, tm time, ts timestamp, cr char(254), vcr varchar(8192), id2 int, id3 int )"); // rl
// real
PreparedStatement ps = conn
.prepareStatement("insert into test values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
String vstr = "ঙ চ ছ জ ঝ ঞ ট This is varchar max upto 8k bytes ... so I suppose this should test long " +
" enought string for now .... with some more bytes added for randomization ";
for (int row = 1; row < 1000; row++) {
ps.setInt(1, row);
ps.setLong(2, row);
ps.setShort(3, (short)row);
ps.setFloat(4, row * 1.3f);
ps.setDouble(5, row + 1.2 / 0.9);
ps.setBigDecimal(6, BigDecimal.valueOf(row / 1.34d));
ps.setBigDecimal(7, BigDecimal.valueOf(row / 1.43d * row));
final int d = ((row % 20) + 1);
ps.setDate(8, java.sql.Date
.valueOf("2011-04-" + (d < 10 ? "0" + d : d)));
ps.setTime(9, java.sql.Time.valueOf("12:00:01"));
ps.setTimestamp(10, java.sql.Timestamp
.valueOf("2011-02-28 11:59:59.99999"));
ps.setString(11, "This is char fixed width upto 254 ... ঋ এ ঐ ও ");
int begin = AvailablePort.rand.nextInt(vstr.length()-1);
ps
.setString(
12, vstr.substring(begin, vstr.length()));
ps.setInt(13, row+1);
ps.setInt(14, row+2);
ps.executeUpdate();
}
GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter() {
private static final long serialVersionUID = 1L;
public int overrideSortBufferSize(ColumnOrdering[] columnOrdering,
int sortBufferMax) {
return 100;
}
public boolean avoidMergeRuns() {
return false;
}
});
// ResultSet rs = st
// .executeQuery("select cr, tm, vcr, dbl, lv, fl, dml, ts, nmr, dt, id from test order by ts, vcr, dt");
// while (rs.next()) {
// System.out.println(rs.getInt("id"));
// }
ResultSet rs = st
.executeQuery("select id, id2, id3, dml, ts from test order by id2 desc, dml");
while (rs.next()) {
System.out.println(rs.getInt("id"));
// TestUtil.getLogger().fine(Integer.toString(rs.getInt("id"));
}
} finally {
GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter());
TestUtil.shutDown();
}
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
ps.setTime(i, new Time(parameter.getTime()));
}
/**
* @param preparedState
* @param param
* @throws SQLException
*/
private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param)
throws SQLException {
boolean isNull = (null == param.getValue());
Class<?> clazz;
try {
clazz = Class.forName(param.getClassName());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
Rep rep = Rep.of(clazz);
switch (rep) {
case PRIMITIVE_CHAR:
case CHARACTER:
case STRING:
preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
break;
case PRIMITIVE_INT:
case INTEGER:
preparedState.setInt(index, isNull ? 0 : Integer.valueOf(param.getValue()));
break;
case PRIMITIVE_SHORT:
case SHORT:
preparedState.setShort(index, isNull ? 0 : Short.valueOf(param.getValue()));
break;
case PRIMITIVE_LONG:
case LONG:
preparedState.setLong(index, isNull ? 0 : Long.valueOf(param.getValue()));
break;
case PRIMITIVE_FLOAT:
case FLOAT:
preparedState.setFloat(index, isNull ? 0 : Float.valueOf(param.getValue()));
break;
case PRIMITIVE_DOUBLE:
case DOUBLE:
preparedState.setDouble(index, isNull ? 0 : Double.valueOf(param.getValue()));
break;
case PRIMITIVE_BOOLEAN:
case BOOLEAN:
preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue()));
break;
case PRIMITIVE_BYTE:
case BYTE:
preparedState.setByte(index, isNull ? 0 : Byte.valueOf(param.getValue()));
break;
case JAVA_UTIL_DATE:
case JAVA_SQL_DATE:
preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
break;
case JAVA_SQL_TIME:
preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
break;
case JAVA_SQL_TIMESTAMP:
preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
break;
default:
preparedState.setObject(index, isNull ? null : param.getValue());
}
}
/** Adding this method to ensure that super class' setInto method doesn't get called
* that leads to the violation of JDBC spec( untyped nulls ) when batching is turned on.
*/
public void setInto(PreparedStatement ps, int position) throws SQLException, StandardException {
ps.setTime(position, getTime((Calendar) null));
}
@Before
public void initTable() throws Exception {
long ts = nextTimestamp();
createTestTable(getUrl(), TO_NUMBER_TABLE_DDL, null, ts-2);
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + ts;
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement(
"upsert into " + TO_NUMBER_TABLE_NAME +
" (a_id, " +
" a_string," +
" b_string," +
" a_date," +
" a_time," +
" a_timestamp)" +
"VALUES (?, ?, ?, ?, ?, ?)");
stmt.setInt(1, 1);
stmt.setString(2, " 1");
stmt.setString(3, " 1");
row1Date = new Date(System.currentTimeMillis() - 1000);
row1Time = new Time(System.currentTimeMillis() - 1000);
row1Timestamp = new Timestamp(System.currentTimeMillis() + 10000);
stmt.setDate(4, row1Date);
stmt.setTime(5, row1Time);
stmt.setTimestamp(6, row1Timestamp);
stmt.execute();
stmt.setInt(1, 2);
stmt.setString(2, " 2.2");
stmt.setString(3, " 2.2");
row2Date = new Date(System.currentTimeMillis() - 10000);
row2Time = new Time(System.currentTimeMillis() - 1234);
row2Timestamp = new Timestamp(System.currentTimeMillis() + 1234567);
stmt.setDate(4, row2Date);
stmt.setTime(5, row2Time);
stmt.setTimestamp(6, row2Timestamp);
stmt.execute();
stmt.setInt(1, 3);
stmt.setString(2, "$3.3");
stmt.setString(3, "$3.3");
row3Date = new Date(System.currentTimeMillis() - 100);
row3Time = new Time(System.currentTimeMillis() - 789);
row3Timestamp = new Timestamp(System.currentTimeMillis() + 78901);
stmt.setDate(4, row3Date);
stmt.setTime(5, row3Time);
stmt.setTimestamp(6, row3Timestamp);
stmt.execute();
conn.commit();
conn.close();
}
@Override
@SuppressWarnings("unchecked")
protected void setStatementParameters(PreparedStatement statement, Object tuple) throws SQLException
{
final int size = columnDataTypes.size();
for (int i = 0; i < size; i++) {
final int type = columnDataTypes.get(i);
ActiveFieldInfo activeFieldInfo = columnFieldGetters.get(i);
switch (type) {
case (Types.CHAR):
case (Types.VARCHAR):
statement.setString(i + 1, ((Getter<Object, String>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.BOOLEAN):
statement.setBoolean(i + 1, ((GetterBoolean<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.TINYINT):
statement.setByte(i + 1, ((PojoUtils.GetterByte<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.SMALLINT):
statement.setShort(i + 1, ((GetterShort<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.INTEGER):
statement.setInt(i + 1, ((GetterInt<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.BIGINT):
statement.setLong(i + 1, ((GetterLong<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.FLOAT):
statement.setFloat(i + 1, ((GetterFloat<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case (Types.DOUBLE):
statement.setDouble(i + 1, ((GetterDouble<Object>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case Types.DECIMAL:
statement.setBigDecimal(i + 1, ((Getter<Object, BigDecimal>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case Types.TIMESTAMP:
statement.setTimestamp(i + 1, ((Getter<Object, Timestamp>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case Types.TIME:
statement.setTime(i + 1, ((Getter<Object, Time>)activeFieldInfo.setterOrGetter).get(tuple));
break;
case Types.DATE:
statement.setDate(i + 1, ((Getter<Object, Date>)activeFieldInfo.setterOrGetter).get(tuple));
break;
default:
handleUnknownDataType(type, tuple, activeFieldInfo);
break;
}
}
}