List of usage examples for java.sql PreparedStatement setObject
default void setObject(int parameterIndex, Object x, SQLType targetSqlType) throws SQLException
From source file:org.apache.torque.util.BasePeerImpl.java
/** * Inserts a record into a database table. * <p>/* w ww .j av a2 s.c o m*/ * If the primary key is included in Criteria, then that value will * be used to insert the row. * <p> * Otherwise, if the primary key can be generated automatically, * the generated key will be used for the insert and will be returned. * <p> * If no value is given for the primary key is defined and it cannot * be generated automatically or the table has no primary key, * the values will be inserted as specified and null will be returned. * * @param insertValues Contains the values to insert, not null. * @param connection the connection to use for the insert, not null. * * @return the primary key of the inserted row (if the table * has a primary key) or null (if the table does not have * a primary key). * * @throws TorqueException if a database error occurs. */ public ObjectKey doInsert(ColumnValues insertValues, Connection connection) throws TorqueException { if (insertValues == null) { throw new TorqueException("insertValues is null"); } if (connection == null) { throw new TorqueException("connection is null"); } String databaseNameFromInsertValues = insertValues.getDbName(); if (databaseNameFromInsertValues == null) { databaseNameFromInsertValues = getDatabaseName(); } Database database = Torque.getDatabase(databaseNameFromInsertValues); Object keyInfo = getIdMethodInfo(); IdGenerator keyGen = database.getIdGenerator(getTableMap().getPrimaryKeyMethod()); SimpleKey id = null; // can currently generate only single column pks, therefore a single // columnMap is ok ColumnMap primaryKey = null; if (keyGen != null) { // fail on multiple pks primaryKey = getTableMap().getPrimaryKey(); // primaryKey will be null if there is no primary key // defined for the table we're inserting into. if (keyGen.isPriorToInsert() && primaryKey != null && !insertValues.containsKey(primaryKey)) { id = getId(primaryKey, keyGen, connection, keyInfo); insertValues.put(primaryKey, new JdbcTypedValue(id.getValue(), id.getJdbcType())); } } List<String> columnNames = new ArrayList<String>(); List<JdbcTypedValue> replacementObjects = new ArrayList<JdbcTypedValue>(); for (Map.Entry<Column, JdbcTypedValue> columnValue : insertValues.entrySet()) { Column column = columnValue.getKey(); columnNames.add(column.getColumnName()); JdbcTypedValue value = columnValue.getValue(); replacementObjects.add(value); } String fullTableName = SqlBuilder.getFullTableName(getTableMap().getFullyQualifiedTableName(), databaseNameFromInsertValues); StringBuilder query = new StringBuilder("INSERT INTO ").append(fullTableName).append("(") .append(StringUtils.join(columnNames, ",")).append(") VALUES ("); for (int i = 0; i < columnNames.size(); ++i) { if (i != 0) { query.append(","); } query.append("?"); } query.append(")"); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(query.toString()); int position = 1; for (JdbcTypedValue replacementObject : replacementObjects) { Object value = replacementObject.getValue(); if (value != null) { if (replacementObject.getJdbcType() != Types.BLOB && replacementObject.getJdbcType() != Types.CLOB) { preparedStatement.setObject(position, value, replacementObject.getJdbcType()); } else { preparedStatement.setObject(position, value); } } else { preparedStatement.setNull(position, replacementObject.getJdbcType()); } position++; } long startTime = System.currentTimeMillis(); log.debug("Executing insert " + query.toString() + " using parameters " + replacementObjects); preparedStatement.executeUpdate(); long queryEndTime = System.currentTimeMillis(); log.trace("insert took " + (queryEndTime - startTime) + " milliseconds"); preparedStatement.close(); preparedStatement = null; } catch (SQLException e) { throw ExceptionMapper.getInstance().toTorqueException(e); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { log.warn("error closing prepared statement", e); } } } // If the primary key column is auto-incremented, get the id // now. if (keyGen != null && keyGen.isPostInsert() && primaryKey != null && !insertValues.containsKey(primaryKey)) { id = getId(primaryKey, keyGen, connection, keyInfo); } return id; }
From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java
/** * Register player/*from w w w .ja v a2 s .c o m*/ * * @param encryptedPassword player's encrypted password * @return a LoginResponse to send the CommandSender ("LOGIN_WENT_ASYNCHRONOUS_SUCCESSFULLY" is a success) * @see Util#encryptString(String) for password encrypting */ public OnlinePlayer.LoginResponse registerPlayer(@NotNull final OnlinePlayer onlinePlayer, @NotNull final String encryptedPassword) { final OfflinePlayer offlinePlayer = onlinePlayer.getOfflinePlayer(); // Check if player is registered if (offlinePlayer.isRegistered()) return OnlinePlayer.LoginResponse.ALREADY_REGISTERED; Bukkit.getScheduler().runTaskAsynchronously(LobsterCraft.plugin, () -> { try { // Set offline player's attributes (lastIp is just set on login) offlinePlayer.lastIp = onlinePlayer.getPlayer().getAddress().getAddress().getHostAddress(); offlinePlayer.encryptedPassword = encryptedPassword; offlinePlayer.databaseState = DatabaseState.INSERT_TO_DATABASE; // Register player on database Connection connection = LobsterCraft.dataSource.getConnection(); // Prepare statement PreparedStatement preparedStatement = connection .prepareStatement("INSERT INTO `minecraft`.`user_profiles`" + "(`playerName`, `password`, `moneyAmount`, `city_cityId`, `cityOccupation`, `lastTimeOnline`, `timePlayed`, `lastIp`)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS); // Set variables preparedStatement.setString(1, offlinePlayer.getPlayerName().toLowerCase()); // Lower case it just to make sure preparedStatement.setString(2, offlinePlayer.getEncryptedPassword()); preparedStatement.setDouble(3, offlinePlayer.getMoneyAmount()); preparedStatement.setObject(4, offlinePlayer.getCityId(), Types.SMALLINT); // Will write null if is null preparedStatement.setObject(5, offlinePlayer.getCityOccupation() != null ? offlinePlayer.getCityOccupation().getOccupationId() : null, Types.TINYINT); preparedStatement.setLong(6, offlinePlayer.getLastTimeOnline()); preparedStatement.setLong(7, offlinePlayer.getTimePlayed()); preparedStatement.setString(8, offlinePlayer.getLastIp()); // Execute statement preparedStatement.execute(); // Retrieve generated keys ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); // Check if key exists if (!generatedKeys.next()) throw new SQLException("Query didn't return any generated key"); offlinePlayer.playerId = generatedKeys.getInt("playerId"); // Close everything generatedKeys.close(); preparedStatement.close(); connection.close(); // Check if was successful if (offlinePlayer.getPlayerId() == null || offlinePlayer.getPlayerId() <= 0) throw new IllegalStateException(Util.appendStrings("Failed to register player: playerId is ", offlinePlayer.getPlayerId())); // Change player's instance location synchronized (playerMapsLock) { unregisteredOfflinePlayers_name.remove(offlinePlayer.getPlayerName(), offlinePlayer); registeredOfflinePlayers_name.put(offlinePlayer.getPlayerName(), offlinePlayer); registeredOfflinePlayers_id.put(offlinePlayer.getPlayerId(), offlinePlayer); // Check if player has a city (even though he just registered...) if (offlinePlayer.getCityId() != null) { if (!registeredOfflinePlayers_cityId.containsKey(offlinePlayer.getCityId())) registeredOfflinePlayers_cityId.put(offlinePlayer.getCityId(), new HashSet<>()); registeredOfflinePlayers_cityId.get(offlinePlayer.getCityId()).add(offlinePlayer); } } // Update database state offlinePlayer.databaseState = DatabaseState.ON_DATABASE; onlinePlayer.onlineState = OnlinePlayer.OnlineState.PRE_LOGIN; // Force login forceLoginPlayer(onlinePlayer); } catch (Exception exception) { exception.printStackTrace(); onlinePlayer.getPlayer().kickPlayer("4Um erro ocorreu ao registrar!"); } }); return OnlinePlayer.LoginResponse.LOGIN_WENT_ASYNCHRONOUS_SUCCESSFULLY; }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index) throws SQLException { switch (targetSqlType) { case Types.INTEGER: pstmt.setInt(index, Integer.parseInt(argument)); break;// ww w .j av a 2s.com case Types.DECIMAL: case Types.NUMERIC: pstmt.setBigDecimal(index, new BigDecimal(argument)); break; case Types.DOUBLE: case Types.FLOAT: pstmt.setDouble(index, Double.parseDouble(argument)); break; case Types.CHAR: case Types.LONGVARCHAR: case Types.VARCHAR: pstmt.setString(index, argument); break; case Types.BIT: case Types.BOOLEAN: pstmt.setBoolean(index, Boolean.parseBoolean(argument)); break; case Types.BIGINT: pstmt.setLong(index, Long.parseLong(argument)); break; case Types.DATE: pstmt.setDate(index, Date.valueOf(argument)); break; case Types.REAL: pstmt.setFloat(index, Float.parseFloat(argument)); break; case Types.TINYINT: pstmt.setByte(index, Byte.parseByte(argument)); break; case Types.SMALLINT: pstmt.setShort(index, Short.parseShort(argument)); break; case Types.TIMESTAMP: pstmt.setTimestamp(index, Timestamp.valueOf(argument)); break; case Types.TIME: pstmt.setTime(index, Time.valueOf(argument)); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: pstmt.setBytes(index, argument.getBytes()); break; case Types.NULL: pstmt.setNull(index, targetSqlType); break; default: pstmt.setObject(index, argument, targetSqlType); } }
From source file:org.springframework.jdbc.object.SqlQueryTests.java
public void testFindCustomerMixed() throws SQLException { MockControl ctrlResultSet2;/*w w w.j a v a 2s. c o m*/ ResultSet mockResultSet2; MockControl ctrlPreparedStatement2; PreparedStatement mockPreparedStatement2; mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getInt("id"); ctrlResultSet.setReturnValue(1); mockResultSet.getString("forename"); ctrlResultSet.setReturnValue("rod"); mockResultSet.next(); ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); mockPreparedStatement.setObject(1, new Integer(1), Types.INTEGER); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.setString(2, "rod"); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.executeQuery(); ctrlPreparedStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); } mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); ctrlResultSet2 = MockControl.createControl(ResultSet.class); mockResultSet2 = (ResultSet) ctrlResultSet2.getMock(); mockResultSet2.next(); ctrlResultSet2.setReturnValue(false); mockResultSet2.close(); ctrlResultSet2.setVoidCallable(); ctrlPreparedStatement2 = MockControl.createControl(PreparedStatement.class); mockPreparedStatement2 = (PreparedStatement) ctrlPreparedStatement2.getMock(); mockPreparedStatement2.setObject(1, new Integer(1), Types.INTEGER); ctrlPreparedStatement2.setVoidCallable(); mockPreparedStatement2.setString(2, "Roger"); ctrlPreparedStatement2.setVoidCallable(); mockPreparedStatement2.executeQuery(); ctrlPreparedStatement2.setReturnValue(mockResultSet2); if (debugEnabled) { mockPreparedStatement2.getWarnings(); ctrlPreparedStatement2.setReturnValue(null); } mockPreparedStatement2.close(); ctrlPreparedStatement2.setVoidCallable(); mockConnection.prepareStatement(SELECT_ID_WHERE); ctrlConnection.setReturnValue(mockPreparedStatement); mockConnection.prepareStatement(SELECT_ID_WHERE); ctrlConnection.setReturnValue(mockPreparedStatement2); ctrlResultSet2.replay(); ctrlPreparedStatement2.replay(); replay(); class CustomerQuery extends MappingSqlQuery { public CustomerQuery(DataSource ds) { super(ds, SELECT_ID_WHERE); declareParameter(new SqlParameter(COLUMN_NAMES[0], COLUMN_TYPES[0])); declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1])); compile(); } protected Object mapRow(ResultSet rs, int rownum) throws SQLException { Customer cust = new Customer(); cust.setId(rs.getInt(COLUMN_NAMES[0])); cust.setForename(rs.getString(COLUMN_NAMES[1])); return cust; } public Customer findCustomer(int id, String name) { return (Customer) findObject(new Object[] { new Integer(id), name }); } } CustomerQuery query = new CustomerQuery(mockDataSource); Customer cust1 = query.findCustomer(1, "rod"); assertTrue("Found customer", cust1 != null); assertTrue("Customer id was assigned correctly", cust1.getId() == 1); Customer cust2 = query.findCustomer(1, "Roger"); assertTrue("No customer found", cust2 == null); }
From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java
/** * This should run on server close, so we don't need to synchronize as every player join is denied before. * * @param connection MySQL connection//w ww .j a va 2 s. c o m * @throws SQLException in case of something going wrong */ private void saveChangedPlayers(@NotNull Connection connection) throws SQLException { long start = System.nanoTime(); int numberOfPlayersUpdated = 0; // Prepare statement PreparedStatement preparedStatement = connection.prepareStatement( "UPDATE `minecraft`.`user_profiles` SET `playerName` = ?, `password` = ?, `moneyAmount` = ?, `city_cityId` = ?," + " `cityOccupation` = ?, `lastTimeOnline` = ?, `timePlayed` = ?, `lastIp` = ? WHERE `playerId` = ?;"); // Iterate through all players for (OfflinePlayer offlinePlayer : registeredOfflinePlayers_id.values()) // Filter the ones needing updates => REGISTERED PLAYERS: they have money amount, passwords, last time online, last IP if (offlinePlayer.getDatabaseState() == DatabaseState.UPDATE_DATABASE) { preparedStatement.setString(1, offlinePlayer.getPlayerName()); preparedStatement.setString(2, offlinePlayer.getEncryptedPassword()); preparedStatement.setDouble(3, offlinePlayer.getMoneyAmount()); preparedStatement.setObject(4, offlinePlayer.getCityId(), Types.INTEGER); // Will write null if is null preparedStatement.setObject(5, offlinePlayer.getCityOccupation() != null ? offlinePlayer.getCityOccupation().getOccupationId() : null, Types.TINYINT); preparedStatement.setLong(6, offlinePlayer.getLastTimeOnline()); preparedStatement.setLong(7, offlinePlayer.getTimePlayed()); preparedStatement.setString(8, offlinePlayer.getLastIp()); preparedStatement.setLong(9, offlinePlayer.getPlayerId()); // Add batch preparedStatement.addBatch(); // Update their database state offlinePlayer.databaseState = DatabaseState.ON_DATABASE; numberOfPlayersUpdated++; } // Execute and announce if (numberOfPlayersUpdated > 0) { preparedStatement.executeBatch(); LobsterCraft.logger.info(Util.appendStrings("Took us ", Util.formatDecimal( (double) (System.nanoTime() - start) / (double) TimeUnit.MILLISECONDS.toNanos(1)), "ms to update ", numberOfPlayersUpdated, " players.")); } // Close statement preparedStatement.close(); }
From source file:net.ontopia.persistence.rdbms.CSVImport.java
public void importCSV(InputStream csvfile) throws Exception { // Execute statements try {//from w w w . ja v a 2 s. c om String[] qmarks = new String[columns.length]; for (int i = 0; i < qmarks.length; i++) { qmarks[i] = "?"; } if (cleartable) { String delsql = "delete from " + table; Statement delstm = conn.createStatement(); delstm.executeUpdate(delsql); //! conn.commit(); } String sql = "insert into " + table + " (" + StringUtils.join(columns, ", ") + ") values (" + StringUtils.join(qmarks, ", ") + ")"; log.debug("SQL: " + sql); PreparedStatement stm = conn.prepareStatement(sql); int datatypes[] = new int[columns.length]; for (int i = 0; i < columns.length; i++) { Table tbl = project.getTableByName(table); if (tbl == null) throw new OntopiaRuntimeException("Unknown table: " + table); Column col = tbl.getColumnByName(columns[i]); if (col == null) throw new OntopiaRuntimeException("Unknown table column: " + columns[i]); if (col.getType() == null) throw new OntopiaRuntimeException("Column type is null: " + col.getType()); DataType datatype = project.getDataTypeByName(col.getType(), "generic"); if (datatype == null) throw new OntopiaRuntimeException("Unknown column type: " + col.getType()); String dtype = datatype.getType(); if ("varchar".equals(dtype)) datatypes[i] = Types.VARCHAR; else if ("integer".equals(dtype)) datatypes[i] = Types.INTEGER; else throw new OntopiaRuntimeException("Unknown datatype: " + dtype); } LineNumberReader reader = new LineNumberReader(new InputStreamReader(csvfile)); // Ignore first X lines for (int i = 0; i < ignorelines; i++) { String line = reader.readLine(); if (line == null) break; } // Process input log.debug("[" + StringUtils.join(columns, ", ") + "]"); int lineno = 0; while (true) { lineno++; String line = reader.readLine(); if (line == null) break; try { String[] cols = StringUtils.split(line, separator); if (cols.length > columns.length && !ignorecolumns) log.debug("Ignoring columns: " + (columns.length + 1) + "-" + cols.length + " '" + line + "'"); log.debug("CVALUES: " + (columns.length + 1) + "-" + cols.length + " '" + line + "'"); String dmesg = "("; for (int i = 0; i < columns.length; i++) { String col = cols[i]; // If first column character is '"' strip quotes. if (stripquotes) { int len = col.length(); if (len > 1 && ((col.charAt(0) == '"' && col.charAt(len - 1) == '"') || (col.charAt(0) == '\'' && col.charAt(len - 1) == '\''))) col = col.substring(1, len - 1); } if (col != null && col.equals("")) col = null; dmesg = dmesg + col; if (i < columns.length - 1) dmesg = dmesg + ", "; stm.setObject(i + 1, col, datatypes[i]); } dmesg = dmesg + ")"; log.debug(dmesg); stm.execute(); } catch (Exception e) { conn.rollback(); throw new OntopiaRuntimeException("Cannot read line " + lineno + ": '" + line + "'", e); } } conn.commit(); } finally { if (conn != null) conn.close(); } }
From source file:org.globus.workspace.persistence.PersistenceAdapterImpl.java
public void setState(int id, int state, Throwable t) throws WorkspaceDatabaseException { if (this.dbTrace) { logger.trace("setState(): " + Lager.id(id) + ", state = " + state); }// w w w . j a va 2 s. com final byte[] faultBytes; try { faultBytes = ErrorUtil.toByteArray(t); } catch (IOException e) { throw new WorkspaceDatabaseException(e); } Connection c = null; PreparedStatement pstmt = null; try { c = getConnection(); pstmt = c.prepareStatement(SQL_SET_STATE); pstmt.setInt(1, state); if (faultBytes != null) { pstmt.setObject(2, faultBytes, Types.BLOB); } else { pstmt.setNull(2, Types.BLOB); } pstmt.setInt(3, id); final int updated = pstmt.executeUpdate(); if (this.dbTrace) { logger.trace(Lager.id(id) + ": updated " + updated + " rows"); } } catch (SQLException e) { logger.error("", e); throw new WorkspaceDatabaseException(e); } finally { try { if (pstmt != null) { pstmt.close(); } if (c != null) { returnConnection(c); } } catch (SQLException sql) { logger.error("SQLException in finally cleanup", sql); } } }
From source file:org.apache.ddlutils.platform.PlatformImplBase.java
/** * This is the core method to set the parameter of a prepared statement to a given value. * The primary purpose of this method is to call the appropriate method on the statement, * and to give database-specific implementations the ability to change this behavior. * /* www .j a va 2s .c om*/ * @param statement The statement * @param sqlIndex The parameter index * @param typeCode The JDBC type code * @param value The value * @throws SQLException If an error occurred while setting the parameter value */ protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value) throws SQLException { if (value == null) { statement.setNull(sqlIndex, typeCode); } else if (value instanceof String) { statement.setString(sqlIndex, (String) value); } else if (value instanceof byte[]) { statement.setBytes(sqlIndex, (byte[]) value); } else if (value instanceof Boolean) { statement.setBoolean(sqlIndex, ((Boolean) value).booleanValue()); } else if (value instanceof Byte) { statement.setByte(sqlIndex, ((Byte) value).byteValue()); } else if (value instanceof Short) { statement.setShort(sqlIndex, ((Short) value).shortValue()); } else if (value instanceof Integer) { statement.setInt(sqlIndex, ((Integer) value).intValue()); } else if (value instanceof Long) { statement.setLong(sqlIndex, ((Long) value).longValue()); } else if (value instanceof BigDecimal) { // setObject assumes a scale of 0, so we rather use the typed setter statement.setBigDecimal(sqlIndex, (BigDecimal) value); } else if (value instanceof Float) { statement.setFloat(sqlIndex, ((Float) value).floatValue()); } else if (value instanceof Double) { statement.setDouble(sqlIndex, ((Double) value).doubleValue()); } else { statement.setObject(sqlIndex, value, typeCode); } }
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 {// w w w . ja v a 2 s .com // 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); } }