List of usage examples for java.sql PreparedStatement setBoolean
void setBoolean(int parameterIndex, boolean x) throws SQLException;
boolean
value. From source file:org.sleuthkit.autopsy.imagegallery.datamodel.DrawableDB.java
private void insertOrUpdateFile(DrawableFile<?> f, DrawableTransaction tr, PreparedStatement stmt) { //TODO: implement batch version -jm if (tr.isClosed()) { throw new IllegalArgumentException("can't update database with closed transaction"); }//from w ww. j a va2 s . co m dbWriteLock(); try { // Update the list of file IDs in memory addImageFileToList(f.getId()); // "INSERT OR IGNORE/ INTO drawable_files (path, name, created_time, modified_time, make, model, analyzed)" stmt.setLong(1, f.getId()); stmt.setString(2, f.getDrawablePath()); stmt.setString(3, f.getName()); stmt.setLong(4, f.getCrtime()); stmt.setLong(5, f.getMtime()); stmt.setString(6, f.getMake()); stmt.setString(7, f.getModel()); stmt.setBoolean(8, f.isAnalyzed()); stmt.executeUpdate(); final Collection<String> hashSetNames = DrawableAttribute.HASHSET.getValue(f); if (hashSetNames.isEmpty() == false) { for (String name : hashSetNames) { // "insert or ignore into hash_sets (hash_set_name) values (?)" insertHashSetStmt.setString(1, name); insertHashSetStmt.executeUpdate(); //TODO: use nested select to get hash_set_id rather than seperate statement/query //"select hash_set_id from hash_sets where hash_set_name = ?" selectHashSetStmt.setString(1, name); try (ResultSet rs = selectHashSetStmt.executeQuery()) { while (rs.next()) { int hashsetID = rs.getInt("hash_set_id"); //"insert or ignore into hash_set_hits (hash_set_id, obj_id) values (?,?)"; insertHashHitStmt.setInt(1, hashsetID); insertHashHitStmt.setLong(2, f.getId()); insertHashHitStmt.executeUpdate(); break; } } } } //and update all groups this file is in for (DrawableAttribute<?> attr : DrawableAttribute.getGroupableAttrs()) { Collection<? extends Comparable<?>> vals = attr.getValue(f); for (Object val : vals) { insertGroup(val.toString(), attr); } } tr.addUpdatedFile(f.getId()); } catch (SQLException | NullPointerException ex) { // This is one of the places where we get an error if the case is closed during processing, // which doesn't need to be reported here. if (Case.isCaseOpen()) { LOGGER.log(Level.SEVERE, "failed to insert/update file" + f.getName(), ex); } } finally { dbWriteUnlock(); } }
From source file:com.concursive.connect.web.modules.login.dao.User.java
public void updateWatch(Connection db, String feature, String value) throws SQLException { String field = null;//from w w w. j a v a2 s . c o m if ("forums".equals(feature)) { field = "watch_forums"; } if (field != null) { PreparedStatement pst = db.prepareStatement("UPDATE users SET " + field + " = ? WHERE user_id = ?"); pst.setBoolean(1, DatabaseUtils.parseBoolean(value)); pst.setInt(2, id); pst.executeUpdate(); pst.close(); // Update the user's session if ("forums".equals(feature)) { watchForums = DatabaseUtils.parseBoolean(value); } CacheUtils.invalidateValue(Constants.SYSTEM_USER_CACHE, id); } }
From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java
@Override public List<Long> findUsedConfigurations(Long domainID) { Connection connection = HarvestDBConnection.get(); try {/*from w ww. j av a2 s . co m*/ List<Long> usedConfigurations = new LinkedList<Long>(); PreparedStatement readUsedConfigurations = connection .prepareStatement(" SELECT configurations.config_id, configurations.name" + " FROM configurations " + " JOIN harvest_configs USING (config_id) " + " JOIN harvestdefinitions USING (harvest_id) " + " WHERE configurations.domain_id = ? " + "AND harvestdefinitions.isactive = ?"); readUsedConfigurations.setLong(1, domainID); readUsedConfigurations.setBoolean(2, true); ResultSet res = readUsedConfigurations.executeQuery(); while (res.next()) { usedConfigurations.add(res.getLong(1)); } readUsedConfigurations.close(); return usedConfigurations; } catch (SQLException e) { throw new IOFailure("SQL Error while reading configuration + " + "seeds lists", e); } finally { HarvestDBConnection.release(connection); } }
From source file:dk.netarkivet.harvester.datamodel.HarvestDefinitionDBDAO.java
/** * Update an existing harvest definition with new info. * * @param hd/*from w w w . ja v a 2s . c o m*/ * An updated harvest definition * @see HarvestDefinitionDAO#update(HarvestDefinition) */ public synchronized void update(HarvestDefinition hd) { ArgumentNotValid.checkNotNull(hd, "HarvestDefinition hd"); if (hd.getOid() == null || !exists(hd.getOid())) { final String message = "Cannot update non-existing " + "harvestdefinition '" + hd.getName() + "'"; log.debug(message); throw new PermissionDenied(message); } HarvestDefinition preHD = null; if (hd instanceof FullHarvest) { preHD = ((FullHarvest) hd).getPreviousHarvestDefinition(); } Connection c = HarvestDBConnection.get(); PreparedStatement s = null; try { c.setAutoCommit(false); s = c.prepareStatement("UPDATE harvestdefinitions SET " + "name = ?, " + "comments = ?, " + "numevents = ?, " + "submitted = ?," + "isactive = ?," + "edition = ?, audience = ? " + "WHERE harvest_id = ? AND edition = ?"); DBUtils.setName(s, 1, hd, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, hd, Constants.MAX_COMMENT_SIZE); s.setInt(3, hd.getNumEvents()); s.setTimestamp(4, new Timestamp(hd.getSubmissionDate().getTime())); s.setBoolean(5, hd.getActive()); long nextEdition = hd.getEdition() + 1; s.setLong(6, nextEdition); s.setString(7, hd.getAudience()); s.setLong(8, hd.getOid()); s.setLong(9, hd.getEdition()); int rows = s.executeUpdate(); // Since the HD exists, no rows indicates bad edition if (rows == 0) { String message = "Somebody else must have updated " + hd + " since edition " + hd.getEdition() + ", not updating"; log.debug(message); throw new PermissionDenied(message); } s.close(); if (hd instanceof FullHarvest) { FullHarvest fh = (FullHarvest) hd; s = c.prepareStatement( "UPDATE fullharvests SET " + "previoushd = ?, " + "maxobjects = ?, " + "maxbytes = ?, " + "maxjobrunningtime = ?, " + "isindexready = ? " + "WHERE harvest_id = ?"); if (preHD != null) { s.setLong(1, preHD.getOid()); } else { s.setNull(1, Types.BIGINT); } s.setLong(2, fh.getMaxCountObjects()); s.setLong(3, fh.getMaxBytes()); s.setLong(4, fh.getMaxJobRunningTime()); s.setBoolean(5, fh.getIndexReady()); s.setLong(6, fh.getOid()); rows = s.executeUpdate(); log.debug(rows + " fullharvests records updated"); } else if (hd instanceof PartialHarvest) { PartialHarvest ph = (PartialHarvest) hd; s = c.prepareStatement( "UPDATE partialharvests SET " + "schedule_id = " + " (SELECT schedule_id FROM schedules " + "WHERE schedules.name = ?), " + "nextdate = ? " + "WHERE harvest_id = ?"); s.setString(1, ph.getSchedule().getName()); DBUtils.setDateMaybeNull(s, 2, ph.getNextDate()); s.setLong(3, ph.getOid()); rows = s.executeUpdate(); log.debug(rows + " partialharvests records updated"); s.close(); // FIXME The updates to harvest_configs table should be done // in method removeDomainConfiguration(), and not here. // The following deletes ALL harvest_configs entries for // this PartialHarvest, and creates the entries for the // PartialHarvest again!! createHarvestConfigsEntries(c, ph, ph.getOid()); } else { String message = "Harvest definition " + hd + " has unknown class " + hd.getClass(); log.warn(message); throw new ArgumentNotValid(message); } saveExtendedFieldValues(c, hd); c.commit(); hd.setEdition(nextEdition); } catch (SQLException e) { throw new IOFailure("SQL error while updating harvest definition " + hd + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); DBUtils.rollbackIfNeeded(c, "updating", hd); HarvestDBConnection.release(c); } }
From source file:orca.registry.DatabaseOperations.java
License:asdf
/** * Insert a new controller into the database * @param simpleName//from ww w. j av a2 s .co m * @param cURL * @param description * @return */ public String insertController(String simpleName, String cUrl, String description, boolean enabled) { if ((simpleName == null) || (cUrl == null) || (description == null)) return "STATUS: ERROR; invalid insert parameters"; log.debug( "Inside DatabaseOperations: insertController() - inserting controller " + simpleName + " " + cUrl); String status = STATUS_SUCCESS; Connection conn = null; // check for image duplicate if (checkImageDuplicate("ctrl_url", cUrl)) { log.error("This registration is invalid, controller " + simpleName + "/" + cUrl + " will not be allowed to register"); return "STATUS: ERROR; duplicate controller URL detected"; } try { //System.out.println("Trying to get a new instance"); log.debug("Inside DatabaseOperations: insertController() - Trying to get a new instance"); Class.forName("com.mysql.jdbc.Driver").newInstance(); //System.out.println("Trying to get a database connection"); log.debug("Inside DatabaseOperations: insertController() - Trying to get a database connection"); conn = DriverManager.getConnection(url, userName, password); //System.out.println ("Database connection established"); log.debug("Inside DatabaseOperations: insertController() - Database connection established"); PreparedStatement pStat = conn.prepareStatement( "INSERT into `Controllers` ( `ctrl_name` , `ctrl_url`, `ctrl_description`, `ctrl_enabled`) values " + "(?, ?, ?, ?)"); pStat.setString(1, simpleName); pStat.setString(2, cUrl); pStat.setString(3, description); pStat.setBoolean(4, enabled); pStat.execute(); pStat.close(); } catch (Exception e) { log.error("DatabaseOperations: insertController() - Error inserting into Controller table: " + e.toString()); status = "STATUS: ERROR; Exception encountered during insertController " + e; } finally { if (conn != null) { try { conn.close(); //System.out.println ("Database connection terminated"); log.debug("Database connection terminated"); } catch (Exception e) { /* ignore close errors */ } } } return status; }
From source file:helma.objectmodel.db.NodeManager.java
private void setStatementValue(PreparedStatement stmt, int stmtNumber, Property p, int columnType) throws SQLException { if (p.getValue() == null) { stmt.setNull(stmtNumber, columnType); } else {/* ww w .j a v a2 s .c o m*/ switch (columnType) { case Types.BIT: case Types.BOOLEAN: stmt.setBoolean(stmtNumber, p.getBooleanValue()); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: stmt.setLong(stmtNumber, p.getIntegerValue()); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: stmt.setDouble(stmtNumber, p.getFloatValue()); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: case Types.BLOB: Object b = p.getJavaObjectValue(); if (b instanceof byte[]) { byte[] buf = (byte[]) b; try { stmt.setBytes(stmtNumber, buf); } catch (SQLException x) { ByteArrayInputStream bout = new ByteArrayInputStream(buf); stmt.setBinaryStream(stmtNumber, bout, buf.length); } } else { throw new SQLException( "expected byte[] for binary column '" + p.getName() + "', found " + b.getClass()); } break; case Types.LONGVARCHAR: try { stmt.setString(stmtNumber, p.getStringValue()); } catch (SQLException x) { String str = p.getStringValue(); Reader r = new StringReader(str); stmt.setCharacterStream(stmtNumber, r, str.length()); } break; case Types.CLOB: String val = p.getStringValue(); Reader isr = new StringReader(val); stmt.setCharacterStream(stmtNumber, isr, val.length()); break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: stmt.setString(stmtNumber, p.getStringValue()); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: stmt.setTimestamp(stmtNumber, p.getTimestampValue()); break; case Types.NULL: stmt.setNull(stmtNumber, 0); break; default: stmt.setString(stmtNumber, p.getStringValue()); break; } } }
From source file:com.uas.document.DocumentDAO.java
@Override public DocumentDTO updateDocument2ParaMove(DocumentDTO dDto) { DocumentDTO dtoViejo = getDocument(dDto); DocumentDTO objectDto = null;/* w ww.j a v a 2 s .co m*/ ResultSet rs = null; Connection c = null; PreparedStatement preparedStmt = null; try { c = DataSourceSingleton.getInstance().getConnection(); String SQL = "update \"public\".\"document\" set \"deleted\"=?,\"backedUp\"=?,\"idArea\"=? where \"id\"=? "; preparedStmt = c.prepareStatement(SQL); preparedStmt.setBoolean(1, dDto.getDeleted()); preparedStmt.setBoolean(2, dDto.getBackedUp()); preparedStmt.setInt(3, dDto.getIdArea()); preparedStmt.setInt(4, dDto.getId()); preparedStmt.executeUpdate(); if (dtoViejo != null && dDto != null) { if ((dtoViejo.getIdArea() != dDto.getIdArea()) && (dDto.getVengoDeRootYPuedoCambiarDeArea())) { DocumentDTO dtoNuevo = getDocument(dDto); if (dDto.getDeleted()) { Files.createDirectories(Paths.get(dtoNuevo.getFullPathToFolderInDeleted()).getParent()); Files.move(Paths.get(dtoViejo.getFullPathToFolderInDeleted()), Paths.get(dtoNuevo.getFullPathToFolderInDeleted())); } else { Files.createDirectories(Paths.get(dtoNuevo.getFullPathToFolder()).getParent()); Files.move(Paths.get(dtoViejo.getFullPathToFolder()), Paths.get(dtoNuevo.getFullPathToFolder())); } } } /* if (!dDto.getBackedUp()){ TransactionRecordFacade tFac = new TransactionRecordFacade(); TransactionRecordDTO tDto = new TransactionRecordDTO(); tDto.getObjectDTO().setId(dDto.getId()); tDto.getTransactionTypeDTO().setId(4); tDto.getUsuarioDTO().setId(dDto.getCreatedBy()); tFac.createTransactionRecord(tDto); } */ } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (c != null) { c.close(); } if (preparedStmt != null) { preparedStmt.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return dDto; }
From source file:fll.web.api.SubjectiveScoresServlet.java
@SuppressFBWarnings(value = { "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns and category are dynamic") @Override//from w ww . j ava 2 s . co m protected final void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { int numModified = 0; final ObjectMapper jsonMapper = new ObjectMapper(); final ServletContext application = getServletContext(); final ChallengeDescription challengeDescription = ApplicationAttributes .getChallengeDescription(application); Connection connection = null; PreparedStatement deletePrep = null; PreparedStatement noShowPrep = null; PreparedStatement insertPrep = null; try { final DataSource datasource = ApplicationAttributes.getDataSource(application); connection = datasource.getConnection(); final int currentTournament = Queries.getCurrentTournament(connection); final StringWriter debugWriter = new StringWriter(); IOUtils.copy(request.getReader(), debugWriter); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Read data: " + debugWriter.toString()); } final Reader reader = new StringReader(debugWriter.toString()); final Map<String, Map<String, Map<Integer, SubjectiveScore>>> allScores = jsonMapper.readValue(reader, ScoresTypeInfo.INSTANCE); for (final Map.Entry<String, Map<String, Map<Integer, SubjectiveScore>>> catEntry : allScores .entrySet()) { final String category = catEntry.getKey(); final ScoreCategory categoryDescription = challengeDescription .getSubjectiveCategoryByName(category); deletePrep = connection.prepareStatement("DELETE FROM " + category // + " WHERE TeamNumber = ?" // + " AND Tournament = ?" // + " AND Judge = ?" // ); deletePrep.setInt(2, currentTournament); noShowPrep = connection.prepareStatement("INSERT INTO " + category // + "(TeamNumber, Tournament, Judge, NoShow) VALUES(?, ?, ?, ?)"); noShowPrep.setInt(2, currentTournament); noShowPrep.setBoolean(4, true); final int NUM_COLUMNS_BEFORE_GOALS = 6; insertPrep = createInsertStatement(connection, categoryDescription); insertPrep.setInt(2, currentTournament); insertPrep.setBoolean(4, false); for (final Map.Entry<String, Map<Integer, SubjectiveScore>> judgeEntry : catEntry.getValue() .entrySet()) { final String judgeId = judgeEntry.getKey(); deletePrep.setString(3, judgeId); noShowPrep.setString(3, judgeId); insertPrep.setString(3, judgeId); for (final Map.Entry<Integer, SubjectiveScore> teamEntry : judgeEntry.getValue().entrySet()) { final int teamNumber = teamEntry.getKey(); final SubjectiveScore score = teamEntry.getValue(); if (score.getModified()) { deletePrep.setInt(1, teamNumber); noShowPrep.setInt(1, teamNumber); insertPrep.setInt(1, teamNumber); insertPrep.setString(5, score.getNote()); ++numModified; if (score.getDeleted()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Deleting team: " + teamNumber + " judge: " + judgeId + " category: " + category); } deletePrep.executeUpdate(); } else if (score.getNoShow()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("NoShow team: " + teamNumber + " judge: " + judgeId + " category: " + category); } deletePrep.executeUpdate(); noShowPrep.executeUpdate(); } else { if (LOGGER.isTraceEnabled()) { LOGGER.trace("scores for team: " + teamNumber + " judge: " + judgeId + " category: " + category); } int goalIndex = 0; for (final AbstractGoal goalDescription : categoryDescription.getGoals()) { if (!goalDescription.isComputed()) { final String goalName = goalDescription.getName(); if (goalDescription.isEnumerated()) { final String value = score.getEnumSubScores().get(goalName); if (null == value) { insertPrep.setNull(goalIndex + NUM_COLUMNS_BEFORE_GOALS, Types.VARCHAR); } else { insertPrep.setString(goalIndex + NUM_COLUMNS_BEFORE_GOALS, value.trim()); } } else { final Double value = score.getStandardSubScores().get(goalName); if (null == value) { insertPrep.setNull(goalIndex + NUM_COLUMNS_BEFORE_GOALS, Types.DOUBLE); } else { insertPrep.setDouble(goalIndex + NUM_COLUMNS_BEFORE_GOALS, value); } } ++goalIndex; } // not computed } // end for deletePrep.executeUpdate(); insertPrep.executeUpdate(); } } // is modified } // foreach team score } // foreach judge SQLFunctions.close(deletePrep); deletePrep = null; SQLFunctions.close(noShowPrep); noShowPrep = null; SQLFunctions.close(insertPrep); insertPrep = null; } // foreach category UploadSubjectiveData.removeNullSubjectiveRows(connection, currentTournament, challengeDescription); final Tournament tournament = Tournament.findTournamentByID(connection, currentTournament); tournament.recordSubjectiveModified(connection); final UploadResult result = new UploadResult(true, "Successfully uploaded scores", numModified); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); jsonMapper.writeValue(writer, result); } catch (final SQLException sqle) { LOGGER.error("Error uploading scores", sqle); final UploadResult result = new UploadResult(false, sqle.getMessage(), numModified); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); jsonMapper.writeValue(writer, result); } finally { SQLFunctions.close(deletePrep); SQLFunctions.close(noShowPrep); SQLFunctions.close(insertPrep); SQLFunctions.close(connection); } }
From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java
/** * Return a Prepared statement for the given Statement object, which is ready to be executed * * @param stmnt SQL stataement to be executed * @param con The connection to be used * @param msgCtx Current message context * @return a PreparedStatement//from w w w. j av a2s .co m * @throws SQLException on error */ protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx) throws SQLException { SynapseLog synLog = getLog(msgCtx); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Getting a connection from DataSource " + getDSName() + " and preparing statement : " + stmnt.getRawStatement()); } if (con == null) { String msg = "Connection from DataSource " + getDSName() + " is null."; log.error(msg); throw new SynapseException(msg); } if (dataSource instanceof BasicDataSource) { BasicDataSource basicDataSource = (BasicDataSource) dataSource; int numActive = basicDataSource.getNumActive(); int numIdle = basicDataSource.getNumIdle(); String connectionId = Integer.toHexString(con.hashCode()); DBPoolView dbPoolView = getDbPoolView(); if (dbPoolView != null) { dbPoolView.setNumActive(numActive); dbPoolView.setNumIdle(numIdle); dbPoolView.updateConnectionUsage(connectionId); } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("[ DB Connection : " + con + " ]"); synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]"); synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]"); synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]"); } } PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement()); // set parameters if any List<Statement.Parameter> params = stmnt.getParameters(); int column = 1; for (Statement.Parameter param : params) { if (param == null) { continue; } String value = (param.getPropertyName() != null ? param.getPropertyName() : param.getXpath().stringValueOf(msgCtx)); if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : " + param.getType() + "(see java.sql.Types for valid " + "types)"); } switch (param.getType()) { // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: { if (value != null && value.length() != 0) { ps.setString(column++, value); } else { ps.setString(column++, null); } break; } case Types.NUMERIC: case Types.DECIMAL: { if (value != null && value.length() != 0) { ps.setBigDecimal(column++, new BigDecimal(value)); } else { ps.setBigDecimal(column++, null); } break; } case Types.BIT: { if (value != null && value.length() != 0) { ps.setBoolean(column++, Boolean.parseBoolean(value)); } else { ps.setNull(column++, Types.BIT); } break; } case Types.TINYINT: { if (value != null && value.length() != 0) { ps.setByte(column++, Byte.parseByte(value)); } else { ps.setNull(column++, Types.TINYINT); } break; } case Types.SMALLINT: { if (value != null && value.length() != 0) { ps.setShort(column++, Short.parseShort(value)); } else { ps.setNull(column++, Types.SMALLINT); } break; } case Types.INTEGER: { if (value != null && value.length() != 0) { ps.setInt(column++, Integer.parseInt(value)); } else { ps.setNull(column++, Types.INTEGER); } break; } case Types.BIGINT: { if (value != null && value.length() != 0) { ps.setLong(column++, Long.parseLong(value)); } else { ps.setNull(column++, Types.BIGINT); } break; } case Types.REAL: { if (value != null && value.length() != 0) { ps.setFloat(column++, Float.parseFloat(value)); } else { ps.setNull(column++, Types.REAL); } break; } case Types.FLOAT: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.FLOAT); } break; } case Types.DOUBLE: { if (value != null && value.length() != 0) { ps.setDouble(column++, Double.parseDouble(value)); } else { ps.setNull(column++, Types.DOUBLE); } break; } // skip BINARY, VARBINARY and LONGVARBINARY case Types.DATE: { if (value != null && value.length() != 0) { ps.setDate(column++, Date.valueOf(value)); } else { ps.setNull(column++, Types.DATE); } break; } case Types.TIME: { if (value != null && value.length() != 0) { ps.setTime(column++, Time.valueOf(value)); } else { ps.setNull(column++, Types.TIME); } break; } case Types.TIMESTAMP: { if (value != null && value.length() != 0) { ps.setTimestamp(column++, Timestamp.valueOf(value)); } else { ps.setNull(column++, Types.TIMESTAMP); } break; } // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT default: { String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : " + column + " and statement : " + stmnt.getRawStatement() + " used by a DB mediator against DataSource : " + getDSName() + " (see java.sql.Types for valid type values)"; handleException(msg, msgCtx); } } } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement() + " against DataSource : " + getDSName()); } return ps; }
From source file:br.com.cobranca.util.Util.java
public static <T> int inserirRegistro(T obj, Connection con) throws Exception { int id = 0;//from w ww. j av a 2 s . c o m String nomeTabela = obj.getClass().getSimpleName(); String strSql = "INSERT INTO " + nomeTabela.toUpperCase() + " ("; boolean usarVirgula = false; for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); if (usarVirgula) { strSql = strSql + ", "; } strSql = strSql + field.getName(); if (!usarVirgula) { usarVirgula = true; } } strSql = strSql + ") VALUES ("; usarVirgula = false; for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); if (usarVirgula) { strSql = strSql + ", "; } strSql = strSql + "?"; if (!usarVirgula) { usarVirgula = true; } } strSql = strSql + ")"; PreparedStatement ps = con.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS); try { int i = 1; for (Field field : obj.getClass().getDeclaredFields()) { String tipoColuna = field.getType().getSimpleName(); if (tipoColuna.toUpperCase().contains("INT")) { tipoColuna = "Int"; } else { tipoColuna = StringPrimeiraLetraMaiuscula(tipoColuna); } // obj . get + nome do campo Method met = obj.getClass().getMethod("get" + StringPrimeiraLetraMaiuscula(field.getName())); if (tipoColuna.equals("Int")) { Integer valor = (Integer) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setInt(i, valor); } } else if (tipoColuna.equals("String")) { String valor = (String) met.invoke(obj); ps.setString(i, valor); } else if (tipoColuna.equals("Double")) { Double valor = (Double) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setDouble(i, valor); } } else if (tipoColuna.equals("Float")) { Float valor = (Float) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setFloat(i, valor); } } else if (tipoColuna.equals("Long")) { Long valor = (Long) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setLong(i, valor); } } else if (tipoColuna.equals("Boolean")) { Boolean valor = (Boolean) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setBoolean(i, valor); } } else if (tipoColuna.equals("Date")) { Date valor = (Date) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setDate(i, new java.sql.Date(valor.getTime())); } } else { return 0; } i++; } int qtdLinhasAfetadas = ps.executeUpdate(); if (qtdLinhasAfetadas > 0) { try (ResultSet rs = ps.getGeneratedKeys()) { if (rs.next()) { id = rs.getInt(1); } } } } catch (Exception ex) { throw new Exception(ex.getMessage()); } finally { ps.close(); } return id; }