List of usage examples for java.sql PreparedStatement setNull
void setNull(int parameterIndex, int sqlType) throws SQLException;
NULL
. From source file:it.fub.jardin.server.DbUtils.java
public int setObjects(final Integer resultsetId, final List<BaseModelData> records, String username) throws HiddenException { int result = 0; Connection connection = this.dbConnectionHandler.getConn(); final String sep = ","; String tableName = null;// ww w. j ava2s . c o m // String set = ""; try { ResultSetMetaData metadata = this.dbProperties.getResultsetMetadata(connection, resultsetId); tableName = metadata.getTableName(1); connection.setAutoCommit(false); for (BaseModelData record : records) { String set = ""; int columns = record.getPropertyNames().size(); for (String property : record.getPropertyNames()) { set += "`" + property + "`=?" + sep; } set = set.substring(0, set.length() - sep.length()); // String query = // "INSERT INTO `" + tableName + "` SET " + set // + " ON DUPLICATE KEY UPDATE " + set; String query = "INSERT INTO `" + tableName + "` SET " + set; PreparedStatement ps = (PreparedStatement) connection.prepareStatement(query); int i = 1; for (String property : record.getPropertyNames()) { Object value = record.get(property); if ((value != null) && (String.valueOf(value).length() > 0)) { ps.setObject(i, record.get(property)); // ps.setObject(i + columns, record.get(property)); } else { ps.setNull(i, java.sql.Types.NULL); // ps.setNull(i + columns, java.sql.Types.NULL); } i++; } // System.out.println(ps.toString()); int num = ps.executeUpdate(); if (num > 0) { String toLog = "INSERT (" + ps.toString() + ")"; // Log.debug(toLog); JardinLogger.debug(username, toLog); } result += num; } connection.commit(); connection.setAutoCommit(true); } catch (MySQLIntegrityConstraintViolationException ex) { try { connection.rollback(); } catch (Exception e) { // TODO Auto-generated catch block JardinLogger.debug(username, "Errore SQL: impossibile eseguire rollback transazione"); e.printStackTrace(); } String message = ex.getLocalizedMessage(); String newMess = ""; // Log.warn("Errore SQL", ex); if (ex.getErrorCode() == 1062) { // updateObjects(resultsetId, records); newMess = newMess.concat(ex.getErrorCode() + " - Errore!!! \n PRIMARY KEY DUPLICATA :\n" + message); } else if (ex.getErrorCode() == 1048) { newMess = newMess .concat(ex.getErrorCode() + " - Errore!!! \n VINCOLO DI INTEGRITA' VIOLATO :\n" + message); } else if (ex.getErrorCode() == 1452) { newMess = newMess .concat(ex.getErrorCode() + " - Errore!!! \n VINCOLO DI FOREIGN KEY VIOLATO :\n" + message); } else { newMess = ex.getErrorCode() + " - Errore!!! \n Problemi sui dati da salvare :\n" + message; } JardinLogger.debug(username, "Errore SQL: " + newMess); throw new HiddenException(newMess); } catch (Exception e) { try { JardinLogger.error(username, "Errore SQL: impossibile eseguire rollback transazione"); connection.rollback(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Log.warn("Errore SQL", e); throw new HiddenException("Errore durante il salvataggio delle modifiche:\n" + e.getLocalizedMessage()); } finally { // JardinLogger.info("Records setted"); this.dbConnectionHandler.closeConn(connection); } return result; }
From source file:org.openbel.framework.internal.KAMStoreDaoImpl.java
/** * {@inheritDoc}//from w w w.j a va 2 s .c om */ @Override public List<Integer> getKamNodeCandidates(FunctionEnum functionType, Namespace namespace, String parameterValue) throws SQLException { // if function is null then delegate to overloaded sibling if (functionType == null) { return getKamNodeCandidates(namespace, parameterValue); } // guard against blank parameter value if (noLength(parameterValue)) { throw new InvalidArgument("parameterValue is blank"); } final Integer objectId = getParameterObjectValueId(parameterValue); if (objectId == null) { // we couldn't find a string for parameterValue, so return no matches return new ArrayList<Integer>(); } PreparedStatement ps = getPreparedStatement(SELECT_KAM_NODE_IDS_FOR_PARAMETER_FUNCTION_SQL); ps.setInt(1, functionType.getValue()); // set namespace to search on, which may be null if (namespace == null || namespace.getId() == null) { ps.setNull(2, Types.INTEGER); ps.setNull(3, Types.INTEGER); } else { final int nid = namespace.getId(); ps.setInt(2, nid); ps.setInt(3, nid); } ps.setInt(4, objectId); return queryForKamNodeCandidates(ps); }
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void insert(final Verblijfsobject verblijfsobject) throws DAOException { try {/*from www. jav a 2 s . c o m*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("insert into bag_verblijfsobject (" + "bag_verblijfsobject_id," + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "officieel," + "verblijfsobject_geometrie," + "oppervlakte_verblijfsobject," + "verblijfsobject_status," + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer," + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setLong(1, verblijfsobject.getIdentificatie()); ps.setInt(2, verblijfsobject.getAanduidingRecordInactief().ordinal()); ps.setLong(3, verblijfsobject.getAanduidingRecordCorrectie()); ps.setInt(4, verblijfsobject.getOfficieel().ordinal()); ps.setString(5, verblijfsobject.getVerblijfsobjectGeometrie()); ps.setInt(6, verblijfsobject.getOppervlakteVerblijfsobject()); ps.setInt(7, verblijfsobject.getVerblijfsobjectStatus().ordinal()); ps.setTimestamp(8, new Timestamp(verblijfsobject.getBegindatumTijdvakGeldigheid().getTime())); if (verblijfsobject.getEinddatumTijdvakGeldigheid() == null) ps.setNull(9, Types.TIMESTAMP); else ps.setTimestamp(9, new Timestamp(verblijfsobject.getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(10, verblijfsobject.getInOnderzoek().ordinal()); ps.setDate(11, new Date(verblijfsobject.getDocumentdatum().getTime())); ps.setString(12, verblijfsobject.getDocumentnummer()); ps.setLong(13, verblijfsobject.getHoofdAdres()); return ps; } }); insertGebruikersdoelen(verblijfsobject); insertNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, verblijfsobject); insertGerelateerdePanden(verblijfsobject); } }); } catch (DataAccessException e) { throw new DAOException("Error inserting verblijfsobject: " + verblijfsobject.getIdentificatie(), e); } }
From source file:com.archivas.clienttools.arcutils.utils.database.ManagedJobSchema.java
/** * Updates the stats for all of the files passed in, and also updates the general job statistics * to reflect how many success/failures there were * /*from w w w. j av a 2 s .co m*/ * @param files * - * @throws DatabaseException * - */ @SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" }) public void markFilesProcessed(Collection<FileStats> files) throws DatabaseException { synchronized (DatabaseResourceManager.DB_LOCK) { PooledDbConnection conn = null; try { conn = connPool.getConnection(); PreparedStatement stmt = conn.prepareStatement(MARK_FILE_PROCESSED_STMT_NAME, markFileProcessedSql); conn.setAutoCommit(false); long totalCnt = 0; long totalSize = 0; long successCnt = 0; long successSize = 0; long failCnt = 0; long failSize = 0; long failDirCnt = 0; for (FileStats file : files) { FileStatus status = file.getStatus(); switch (status) { case SUCCEEDED: { if (file.includeInStats()) { successCnt++; successSize += file.getSize(); } break; } case FAILED: { if (file.includeInStats()) { failCnt++; failSize += file.getSize(); if (file.failedDuringFind()) { // in this case we need to increment the total counts as well totalCnt++; totalSize += file.getSize(); // probably zero since we didn't // get that far } } if (file.getArcProcssFile().isDirectory()) { failDirCnt++; } break; } default: throw new RuntimeException("Unsupported file status: " + status); } stmt.clearParameters(); stmt.setInt(1, file.getStatus().ordinal()); stmt.setInt(2, file.getRetries()); Date startTime = file.getStartTime(); if (startTime != null) { stmt.setLong(3, startTime.getTime()); } else { stmt.setNull(3, java.sql.Types.BIGINT); } Date endTime = file.getEndTime(); if (endTime != null) { stmt.setLong(4, endTime.getTime()); } else { stmt.setNull(4, java.sql.Types.BIGINT); } stmt.setLong(5, file.getRunTimeMs()); if (file.getException() == null) { stmt.setNull(6, java.sql.Types.VARCHAR); } else { stmt.setString(6, file.getException().getMessage()); } if (file.getStatusCode() == null) { stmt.setNull(7, java.sql.Types.INTEGER); } else { stmt.setInt(7, file.getStatusCode()); } stmt.setLong(8, file.getDatabaseRecordId()); stmt.addBatch(); } // execute the batch statment to update all of the file rows stmt.executeBatch(); // now update overall job stats to reflect these changes ManagedJobsSchema.getInstance().updateProcessedFilesStats(conn, jobId, totalCnt, totalSize, successCnt, successSize, failCnt, failSize, failDirCnt); conn.commit(); } catch (Exception e) { rollback(conn); throw new DatabaseException(DBUtils.getErrorMessage( "An error occurred updating file stats on table " + qualifiedFilesTableName, e), e); } finally { connPool.returnConnection(conn); } } }
From source file:org.openbel.framework.internal.KAMStoreDaoImpl.java
@SuppressWarnings("unchecked") @Override/*from w ww .java 2s . c om*/ public Integer getKamNodeId(String belTermString) throws SQLException { // See if the bel term is already mapped if (supportingTermLabelReverseCache.containsKey(belTermString)) { return supportingTermLabelReverseCache.get(belTermString); } // parse the BelTerm Term term; try { term = BELParser.parseTerm(belTermString); } catch (Exception e) { // invalid BEL return null; } Collection<Integer> possibleTermIds = null; int ordinal = 0; for (Parameter param : term.getAllParametersLeftToRight()) { Integer namespaceId = null; if (param.getNamespace() != null && StringUtils.isNotBlank(param.getNamespace().getPrefix())) { Namespace ns = getNamespaceByPrefix(param.getNamespace().getPrefix()); if (ns != null) { namespaceId = ns.getId(); } } String paramValue = param.getValue(); if (paramValue.startsWith("\"") && paramValue.endsWith("\"")) { paramValue = paramValue.substring(1, paramValue.length() - 1); } Integer valueOid = getObjectIdByValue(paramValue); if (valueOid == null) { // could not find label for param if (possibleTermIds != null) { possibleTermIds.clear(); } break; } ResultSet rset = null; try { PreparedStatement ps = getPreparedStatement(SELECT_TERM_ID_BY_PARAMETERS_SQL); // set twice to handle is null, see http://stackoverflow.com/questions/4215135/ if (namespaceId == null) { ps.setNull(1, Types.INTEGER); ps.setNull(2, Types.INTEGER); } else { ps.setInt(1, namespaceId); ps.setInt(2, namespaceId); } ps.setInt(3, valueOid); ps.setInt(4, ordinal); rset = ps.executeQuery(); Set<Integer> termIdsWithParam = new HashSet<Integer>(); while (rset.next()) { termIdsWithParam.add(rset.getInt(1)); } if (possibleTermIds == null) { // first param possibleTermIds = termIdsWithParam; } else { possibleTermIds = CollectionUtils.intersection(possibleTermIds, termIdsWithParam); } } finally { close(rset); } // no need to continue to next param if possibleTermIds is empty if (possibleTermIds.isEmpty()) { break; } ordinal++; } Integer kamNodeId = null; // iterate over all possible terms and check for label matches if (possibleTermIds != null) { for (Integer termId : possibleTermIds) { BelTerm belTerm = getBelTermById(termId); if (belTerm.getLabel().equals(belTermString)) { kamNodeId = getKamNodeId(belTerm); break; } } } if (kamNodeId != null) { supportingTermLabelReverseCache.put(belTermString, kamNodeId); } return kamNodeId; }
From source file:dk.netarkivet.harvester.datamodel.HarvestDefinitionDBDAO.java
/** * Create a harvest definition in Database. The harvest definition object * should not have its ID set unless we are in the middle of migrating. * * @param harvestDefinition// w w w.ja v a2s . c o m * A new harvest definition to store in the database. * @return The harvestId for the just created harvest definition. * @see HarvestDefinitionDAO#create(HarvestDefinition) */ @Override public synchronized Long create(HarvestDefinition harvestDefinition) { Connection connection = HarvestDBConnection.get(); PreparedStatement s = null; try { Long id = harvestDefinition.getOid(); if (id == null) { id = generateNextID(connection); } connection.setAutoCommit(false); s = connection.prepareStatement( "INSERT INTO harvestdefinitions " + "( harvest_id, name, comments, numevents, submitted," + " isactive, edition, audience ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?,? )"); s.setLong(1, id); DBUtils.setName(s, 2, harvestDefinition, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 3, harvestDefinition, Constants.MAX_COMMENT_SIZE); s.setLong(4, harvestDefinition.getNumEvents()); Date submissiondate = new Date(); // Don't set on object, as we may yet rollback s.setTimestamp(5, new Timestamp(submissiondate.getTime())); s.setBoolean(6, harvestDefinition.getActive()); final int edition = 1; s.setLong(7, edition); s.setString(8, harvestDefinition.getAudience()); s.executeUpdate(); s.close(); if (harvestDefinition instanceof FullHarvest) { FullHarvest fh = (FullHarvest) harvestDefinition; s = connection.prepareStatement("INSERT INTO fullharvests " + "( harvest_id, maxobjects, maxbytes," + " maxjobrunningtime, previoushd, isindexready)" + "VALUES ( ?, ?, ?, ?, ?, ? )"); s.setLong(1, id); s.setLong(2, fh.getMaxCountObjects()); s.setLong(3, fh.getMaxBytes()); s.setLong(4, fh.getMaxJobRunningTime()); if (fh.getPreviousHarvestDefinition() != null) { s.setLong(5, fh.getPreviousHarvestDefinition().getOid()); } else { s.setNull(5, Types.BIGINT); } s.setBoolean(6, fh.getIndexReady()); s.executeUpdate(); } else if (harvestDefinition instanceof PartialHarvest) { PartialHarvest ph = (PartialHarvest) harvestDefinition; // Get schedule id long scheduleId = DBUtils.selectLongValue(connection, "SELECT schedule_id FROM schedules WHERE name = ?", ph.getSchedule().getName()); s = connection.prepareStatement("INSERT INTO partialharvests " + "( harvest_id, schedule_id, nextdate ) " + "VALUES ( ?, ?, ? )"); s.setLong(1, id); s.setLong(2, scheduleId); DBUtils.setDateMaybeNull(s, 3, ph.getNextDate()); s.executeUpdate(); createHarvestConfigsEntries(connection, ph, id); } else { String message = "Harvest definition " + harvestDefinition + " is of unknown class " + harvestDefinition.getClass(); log.warn(message); throw new ArgumentNotValid(message); } connection.commit(); // Now that we have committed, set new data on object. harvestDefinition.setSubmissionDate(submissiondate); harvestDefinition.setEdition(edition); harvestDefinition.setOid(id); // saving after receiving id saveExtendedFieldValues(connection, harvestDefinition); return id; } catch (SQLException e) { String message = "SQL error creating harvest definition " + harvestDefinition + " in database" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(s); DBUtils.rollbackIfNeeded(connection, "creating", harvestDefinition); HarvestDBConnection.release(connection); } }
From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java
/** * Runs the udpateChangeset prepared statement. * <code>//from w ww. j a v a 2s .c o m * UPDATE {0} SET ADDGRAPH=?,REMOVEGRAPH=? ,METAADDGRAPH=?,METAREMOVEGRAPH=? WHERE ID=? * </code> * *@param stmtProvider * factory and cache of PreparedStatments *@param connection * connection to underlying database * *@param addGraph template parameter *@param removeGraph template parameter *@param addMetaGraph template parameter *@param removeMetaGraph template parameter *@param id template parameter * *@param transactionTableName template parameter *@return int *@throws org.openanzo.jdbc.utils.RdbException */ public static int udpateChangeset(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider, final java.sql.Connection connection, java.sql.Clob addGraph, java.sql.Clob removeGraph, java.sql.Clob addMetaGraph, java.sql.Clob removeMetaGraph, long id, String transactionTableName) throws org.openanzo.jdbc.utils.RdbException { java.sql.PreparedStatement ps = null; //long startTimer=System.currentTimeMillis(); try { ps = stmtProvider.getPreparedSQLStatement(udpateChangeset, new String[] { transactionTableName }, connection); int argc = 1; if (addGraph == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, addGraph); } if (removeGraph == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, removeGraph); } if (addMetaGraph == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, addMetaGraph); } if (removeMetaGraph == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, removeMetaGraph); } ps.setLong(argc++, id); int counter = 0; try { counter = ps.executeUpdate(); } catch (java.sql.SQLException sqle) { if (sqle.getErrorCode() == 1205) { int retries = 0; while (retries < 5) { try { Thread.sleep(5000); } catch (InterruptedException ie) { throw sqle; } try { counter = ps.executeUpdate(); break; } catch (java.sql.SQLException sqleInner) { if (sqleInner.getErrorCode() == 1205) { retries++; } else { throw sqleInner; } } } if (retries >= 5) { throw sqle; } } else { throw sqle; } } return counter; } catch (java.sql.SQLException e) { throw new org.openanzo.jdbc.utils.RdbException( org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "udpateChangeset", stmtProvider.getSqlString(udpateChangeset), "" + "addGraph=" + ((addGraph != null) ? addGraph.toString() : "null") + "," + "removeGraph=" + ((removeGraph != null) ? removeGraph.toString() : "null") + "," + "addMetaGraph=" + ((addMetaGraph != null) ? addMetaGraph.toString() : "null") + "," + "removeMetaGraph=" + ((removeMetaGraph != null) ? removeMetaGraph.toString() : "null") + "," + "id=" + (id), "" + "transactionTableName=" + ((transactionTableName != null) ? transactionTableName.toString() : "null")); } finally { if (ps != null) { try { ps.close(); } catch (java.sql.SQLException sqle) { if (log.isDebugEnabled()) log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement", sqle); } } //long endtimer=(System.currentTimeMillis()-startTimer); //if(endtimer>CUTOFF)System.out.println("[udpateChangeset]"+endtimer); } }
From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java
@Override public void insertConnectorMessage(ConnectorMessage connectorMessage, boolean storeMaps, boolean updateStats) { logger.debug(connectorMessage.getChannelId() + "/" + connectorMessage.getMessageId() + "/" + connectorMessage.getMetaDataId() + ": inserting connector message with" + (storeMaps ? "" : "out") + " maps"); try {/*w ww . j a v a 2 s.c o m*/ PreparedStatement statement = prepareStatement("insertConnectorMessage", connectorMessage.getChannelId()); statement.setInt(1, connectorMessage.getMetaDataId()); statement.setLong(2, connectorMessage.getMessageId()); statement.setString(3, connectorMessage.getServerId()); statement.setTimestamp(4, new Timestamp(connectorMessage.getReceivedDate().getTimeInMillis())); statement.setString(5, Character.toString(connectorMessage.getStatus().getStatusCode())); if (connectorMessage.getConnectorName() == null) { statement.setNull(6, Types.VARCHAR); } else { statement.setString(6, connectorMessage.getConnectorName()); } statement.setInt(7, connectorMessage.getSendAttempts()); if (connectorMessage.getSendDate() == null) { statement.setNull(8, Types.TIMESTAMP); } else { statement.setTimestamp(8, new Timestamp(connectorMessage.getSendDate().getTimeInMillis())); } if (connectorMessage.getResponseDate() == null) { statement.setNull(9, Types.TIMESTAMP); } else { statement.setTimestamp(9, new Timestamp(connectorMessage.getResponseDate().getTimeInMillis())); } statement.setInt(10, connectorMessage.getErrorCode()); statement.setInt(11, connectorMessage.getChainId()); statement.setInt(12, connectorMessage.getOrderId()); statement.executeUpdate(); if (storeMaps) { updateSourceMap(connectorMessage); updateMaps(connectorMessage); } updateErrors(connectorMessage); if (updateStats) { transactionStats.update(connectorMessage.getChannelId(), connectorMessage.getMetaDataId(), connectorMessage.getStatus(), null); } } catch (SQLException e) { throw new DonkeyDaoException(e); } }
From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java
/** * Runs the insertCommand prepared statement. * <code>/* w w w.j a va 2s . c o m*/ * INSERT INTO {0} (transactionId, commandType,context,prereq) VALUES (?, ?, ?, ?) * </code> * *@param stmtProvider * factory and cache of PreparedStatments *@param connection * connection to underlying database * *@param transactionId template parameter *@param commandType template parameter *@param context template parameter *@param preReq template parameter * *@param transactionTableName template parameter *@return int *@throws org.openanzo.jdbc.utils.RdbException */ public static int insertCommand(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider, final java.sql.Connection connection, long transactionId, String commandType, java.sql.Clob context, java.sql.Clob preReq, String transactionTableName) throws org.openanzo.jdbc.utils.RdbException { java.sql.PreparedStatement ps = null; //long startTimer=System.currentTimeMillis(); try { ps = stmtProvider.getPreparedSQLStatement(insertCommand, new String[] { transactionTableName }, connection); int argc = 1; ps.setLong(argc++, transactionId); if (commandType == null) { ps.setNull(argc++, java.sql.Types.VARCHAR); } else { ps.setString(argc++, commandType); } if (context == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, context); } if (preReq == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, preReq); } int counter = 0; try { counter = ps.executeUpdate(); } catch (java.sql.SQLException sqle) { if (sqle.getErrorCode() == 1205) { int retries = 0; while (retries < 5) { try { Thread.sleep(5000); } catch (InterruptedException ie) { throw sqle; } try { counter = ps.executeUpdate(); break; } catch (java.sql.SQLException sqleInner) { if (sqleInner.getErrorCode() == 1205) { retries++; } else { throw sqleInner; } } } if (retries >= 5) { throw sqle; } } else { throw sqle; } } return counter; } catch (java.sql.SQLException e) { throw new org.openanzo.jdbc.utils.RdbException( org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "insertCommand", stmtProvider.getSqlString(insertCommand), "" + "transactionId=" + (transactionId) + "," + "commandType=" + ((commandType != null) ? commandType.toString() : "null") + "," + "context=" + ((context != null) ? context.toString() : "null") + "," + "preReq=" + ((preReq != null) ? preReq.toString() : "null"), "" + "transactionTableName=" + ((transactionTableName != null) ? transactionTableName.toString() : "null")); } finally { if (ps != null) { try { ps.close(); } catch (java.sql.SQLException sqle) { if (log.isDebugEnabled()) log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement", sqle); } } //long endtimer=(System.currentTimeMillis()-startTimer); //if(endtimer>CUTOFF)System.out.println("[insertCommand]"+endtimer); } }
From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java
/** * Runs the updateCommand prepared statement. * <code>/*from w w w . j a va 2s . c o m*/ * UPDATE {0} set transactionId=?,commandType=?,context=?,preReq=? where id=? * </code> * *@param stmtProvider * factory and cache of PreparedStatments *@param connection * connection to underlying database * *@param transactionId template parameter *@param commandType template parameter *@param context template parameter *@param preReq template parameter *@param id template parameter * *@param transactionTableName template parameter *@return int *@throws org.openanzo.jdbc.utils.RdbException */ public static int updateCommand(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider, final java.sql.Connection connection, long transactionId, String commandType, java.sql.Clob context, java.sql.Clob preReq, long id, String transactionTableName) throws org.openanzo.jdbc.utils.RdbException { java.sql.PreparedStatement ps = null; //long startTimer=System.currentTimeMillis(); try { ps = stmtProvider.getPreparedSQLStatement(updateCommand, new String[] { transactionTableName }, connection); int argc = 1; ps.setLong(argc++, transactionId); if (commandType == null) { ps.setNull(argc++, java.sql.Types.VARCHAR); } else { ps.setString(argc++, commandType); } if (context == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, context); } if (preReq == null) { ps.setNull(argc++, java.sql.Types.CLOB); } else { ps.setClob(argc++, preReq); } ps.setLong(argc++, id); int counter = 0; try { counter = ps.executeUpdate(); } catch (java.sql.SQLException sqle) { if (sqle.getErrorCode() == 1205) { int retries = 0; while (retries < 5) { try { Thread.sleep(5000); } catch (InterruptedException ie) { throw sqle; } try { counter = ps.executeUpdate(); break; } catch (java.sql.SQLException sqleInner) { if (sqleInner.getErrorCode() == 1205) { retries++; } else { throw sqleInner; } } } if (retries >= 5) { throw sqle; } } else { throw sqle; } } return counter; } catch (java.sql.SQLException e) { throw new org.openanzo.jdbc.utils.RdbException( org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "updateCommand", stmtProvider.getSqlString(updateCommand), "" + "transactionId=" + (transactionId) + "," + "commandType=" + ((commandType != null) ? commandType.toString() : "null") + "," + "context=" + ((context != null) ? context.toString() : "null") + "," + "preReq=" + ((preReq != null) ? preReq.toString() : "null") + "," + "id=" + (id), "" + "transactionTableName=" + ((transactionTableName != null) ? transactionTableName.toString() : "null")); } finally { if (ps != null) { try { ps.close(); } catch (java.sql.SQLException sqle) { if (log.isDebugEnabled()) log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement", sqle); } } //long endtimer=(System.currentTimeMillis()-startTimer); //if(endtimer>CUTOFF)System.out.println("[updateCommand]"+endtimer); } }