List of usage examples for java.sql PreparedStatement setNull
void setNull(int parameterIndex, int sqlType) throws SQLException;
NULL
. From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java
/** * Runs the insertChangeset prepared statement. * <code>/*from w ww . ja v a2s. co m*/ * INSERT INTO {0} (commandId, addGraph,removeGraph,metaddgraph,metaremovegraph,namedGraphUri) VALUES (?, ?, ?, ?,?,?) * </code> * *@param stmtProvider * factory and cache of PreparedStatments *@param connection * connection to underlying database * *@param commandId template parameter *@param addGraph template parameter *@param removeGraph template parameter *@param addMetaGraph template parameter *@param removeMetaGraph template parameter *@param uri template parameter * *@param transactionTableName template parameter *@return int *@throws org.openanzo.jdbc.utils.RdbException */ public static int insertChangeset(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider, final java.sql.Connection connection, long commandId, java.sql.Clob addGraph, java.sql.Clob removeGraph, java.sql.Clob addMetaGraph, java.sql.Clob removeMetaGraph, String uri, String transactionTableName) throws org.openanzo.jdbc.utils.RdbException { java.sql.PreparedStatement ps = null; //long startTimer=System.currentTimeMillis(); try { ps = stmtProvider.getPreparedSQLStatement(insertChangeset, new String[] { transactionTableName }, connection); int argc = 1; ps.setLong(argc++, commandId); 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); } if (uri == null) { ps.setNull(argc++, java.sql.Types.VARCHAR); } else { ps.setString(argc++, uri); } 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, "insertChangeset", stmtProvider.getSqlString(insertChangeset), "" + "commandId=" + (commandId) + "," + "addGraph=" + ((addGraph != null) ? addGraph.toString() : "null") + "," + "removeGraph=" + ((removeGraph != null) ? removeGraph.toString() : "null") + "," + "addMetaGraph=" + ((addMetaGraph != null) ? addMetaGraph.toString() : "null") + "," + "removeMetaGraph=" + ((removeMetaGraph != null) ? removeMetaGraph.toString() : "null") + "," + "uri=" + ((uri != null) ? uri.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("[insertChangeset]"+endtimer); } }
From source file:org.globus.workspace.persistence.PersistenceAdapterImpl.java
public void setNetwork(int id, String network) throws WorkspaceDatabaseException { if (this.dbTrace) { logger.trace("setNetwork(): " + Lager.id(id) + ", network = " + network); }/*from ww w . j a v a 2 s . com*/ Connection c = null; PreparedStatement pstmt = null; try { c = getConnection(); pstmt = c.prepareStatement(SQL_SET_NETWORKING); if (network != null) { pstmt.setString(1, network); } else { pstmt.setNull(1, Types.VARCHAR); } pstmt.setInt(2, 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.globus.workspace.persistence.PersistenceAdapterImpl.java
public void setHostname(int id, String hostname) throws WorkspaceDatabaseException { if (this.dbTrace) { logger.trace("setHostname(): " + Lager.id(id) + ", hostname = " + hostname); }/*from w w w . ja v a 2s. c o m*/ Connection c = null; PreparedStatement pstmt = null; try { c = getConnection(); pstmt = c.prepareStatement(SQL_SET_HOSTNAME); if (hostname != null) { pstmt.setString(1, hostname); } else { pstmt.setNull(1, Types.VARCHAR); } pstmt.setInt(2, 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.globus.workspace.persistence.PersistenceAdapterImpl.java
private void addGroupOrEnsemble(String id, String creatorDN) throws WorkspaceDatabaseException { if (id == null) { throw new IllegalArgumentException("id is null"); }/* w ww . j a v a 2 s.c om*/ Connection c = null; PreparedStatement pstmt = null; try { c = getConnection(); pstmt = c.prepareStatement(SQL_INSERT_GROUP_RESOURCE); pstmt.setString(1, id); if (creatorDN != null) { pstmt.setString(2, creatorDN); } else { pstmt.setNull(2, Types.VARCHAR); } pstmt.executeUpdate(); } 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.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 va2 s . c om 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.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * Save given inputs to the database.// www . ja v a 2 s.c o m * * Use given prepare statement to save all inputs into repository. * * @param configId Identifier for corresponding config * @param inputs List of inputs that needs to be saved * @param baseInputStmt Statement that we can utilize * @throws SQLException In case of any failure on Derby side */ private void registerConfigInputs(long configId, List<MInput<?>> inputs, PreparedStatement baseInputStmt) throws SQLException { short inputIndex = 0; for (MInput<?> input : inputs) { baseInputStmt.setString(1, input.getName()); baseInputStmt.setLong(2, configId); baseInputStmt.setShort(3, inputIndex++); baseInputStmt.setString(4, input.getType().name()); baseInputStmt.setBoolean(5, input.isSensitive()); // String specific column(s) if (input.getType().equals(MInputType.STRING)) { MStringInput strInput = (MStringInput) input; baseInputStmt.setShort(6, strInput.getMaxLength()); } else { baseInputStmt.setNull(6, Types.INTEGER); } // Enum specific column(s) if (input.getType() == MInputType.ENUM) { baseInputStmt.setString(7, StringUtils.join(((MEnumInput) input).getValues(), ",")); } else { baseInputStmt.setNull(7, Types.VARCHAR); } int baseInputCount = baseInputStmt.executeUpdate(); if (baseInputCount != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0017, Integer.toString(baseInputCount)); } ResultSet rsetInputId = baseInputStmt.getGeneratedKeys(); if (!rsetInputId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0018); } long inputId = rsetInputId.getLong(1); input.setPersistenceId(inputId); } }
From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java
/** * Update the pagetemplate in the database. * * @param doc The pagetemplate XML document. * @throws VerticalUpdateException Indicates that the update was not successfull. *//*from ww w. j a v a2s . com*/ private void updatePageTemplate(Document doc) throws VerticalUpdateException { Element docElem = doc.getDocumentElement(); Element[] pagetemplateElems; if ("pagetemplate".equals(docElem.getTagName())) { pagetemplateElems = new Element[] { docElem }; } else { pagetemplateElems = XMLTool.getElements(doc.getDocumentElement()); } Connection con = null; PreparedStatement preparedStmt = null; int pageTemplateKey; try { con = getConnection(); preparedStmt = con.prepareStatement(PAT_UPDATE); for (Element root : pagetemplateElems) { Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes()); // attribute: key String tmp = root.getAttribute("key"); pageTemplateKey = Integer.parseInt(tmp); preparedStmt.setInt(9, pageTemplateKey); // attribute: type PageTemplateType pageTemplateType = PageTemplateType .valueOf(root.getAttribute("type").toUpperCase()); preparedStmt.setInt(7, pageTemplateType.getKey()); RunAsType runAs = RunAsType.INHERIT; String runAsStr = root.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(8, runAs.getKey()); // attribute: menukey tmp = root.getAttribute("menukey"); int menuKey = Integer.parseInt(tmp); preparedStmt.setInt(2, menuKey); // element: stylesheet Element stylesheet = subelems.get("stylesheet"); String styleSheetKey = stylesheet.getAttribute("stylesheetkey"); preparedStmt.setString(1, styleSheetKey); // element: name Element subelem = subelems.get("name"); String name = XMLTool.getElementText(subelem); preparedStmt.setString(3, name); subelem = subelems.get("description"); if (subelem != null) { String description = XMLTool.getElementText(subelem); if (description != null) { preparedStmt.setString(4, description); } else { preparedStmt.setNull(4, Types.VARCHAR); } } else { preparedStmt.setNull(4, Types.VARCHAR); } // element: timestamp (using the database timestamp at creation) /* no code */ // element: contenttypes subelem = subelems.get("contenttypes"); Element[] ctyElems = XMLTool.getElements(subelem); int[] ctys = new int[ctyElems.length]; for (int j = 0; j < ctyElems.length; j++) { ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key")); } setPageTemplateContentTypes(pageTemplateKey, ctys); // element: datasources subelem = subelems.get("pagetemplatedata"); Document ptdDoc = XMLTool.createDocument(); ptdDoc.appendChild(ptdDoc.importNode(subelem, true)); byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8"); ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes); preparedStmt.setBinaryStream(5, byteStream, ptdBytes.length); // element: CSS subelem = subelems.get("css"); if (subelem != null) { String foo = subelem.getAttribute("stylesheetkey"); preparedStmt.setString(6, foo); } else { preparedStmt.setNull(6, Types.VARCHAR); } int result = preparedStmt.executeUpdate(); if (result <= 0) { String message = "Failed to update page template. No page template updated."; VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null); } // If page template is of type "section", we need to create sections for menuitems // that does not have one if (pageTemplateType == PageTemplateType.SECTIONPAGE) { int[] menuItemKeys = getMenuItemKeysByPageTemplate(pageTemplateKey); for (int menuItemKey : menuItemKeys) { MenuItemKey sectionKey = getSectionHandler() .getSectionKeyByMenuItem(new MenuItemKey(menuItemKey)); if (sectionKey == null) { getSectionHandler().createSection(menuItemKey, true, ctys); } } } Element contentobjects = XMLTool.getElement(root, "contentobjects"); Element ptp = XMLTool.getElement(root, "pagetemplateparameters"); if (ptp != null) { int[] paramKeys = new int[0]; // update all ptp entries for page try { int[] oldPTPKey = getPageTemplParamKeys(pageTemplateKey); Node[] ptpNode = XMLTool.filterNodes(ptp.getChildNodes(), Node.ELEMENT_NODE); int[] updatedPTPKey = new int[ptpNode.length]; int updatedPTPs = 0, newPTPs = 0; Document updatedPTPDoc = XMLTool.createDocument("pagetemplateparameters"); Element updatedPTP = updatedPTPDoc.getDocumentElement(); Document newPTPDoc = XMLTool.createDocument("pagetemplateparameters"); Element newPTP = newPTPDoc.getDocumentElement(); for (Node aPtpNode : ptpNode) { ptp = (Element) aPtpNode; String keyStr = ptp.getAttribute("key"); int key; if (keyStr != null && keyStr.length() > 0) { key = Integer.parseInt(keyStr); } else { key = -1; } if (key >= 0) { updatedPTP.appendChild(updatedPTPDoc.importNode(ptp, true)); updatedPTPKey[updatedPTPs++] = key; } else { newPTP.appendChild(newPTPDoc.importNode(ptp, true)); newPTPs++; } } // remove old if (updatedPTPs == 0) { PageHandler pageHandler = getPageHandler(); int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey); for (int pageKey : pageKeys) { pageHandler.removePageContentObjects(pageKey, null); } removePageTemplateCOs(pageTemplateKey, null); removePageTemplParams(pageTemplateKey); } else if (updatedPTPs < oldPTPKey.length) { int temp1[] = new int[updatedPTPs]; System.arraycopy(updatedPTPKey, 0, temp1, 0, updatedPTPs); updatedPTPKey = temp1; Arrays.sort(oldPTPKey); oldPTPKey = ArrayUtil.removeDuplicates(oldPTPKey); Arrays.sort(updatedPTPKey); updatedPTPKey = ArrayUtil.removeDuplicates(updatedPTPKey); int temp2[][] = ArrayUtil.diff(oldPTPKey, updatedPTPKey); PageHandler pageHandler = getPageHandler(); int[] contentObjectKeys = pageHandler.getContentObjectKeys(temp2[0]); int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey); if (contentObjectKeys != null && contentObjectKeys.length > 0) { for (int pageKey : pageKeys) { pageHandler.removePageContentObjects(pageKey, contentObjectKeys); } } removePageTemplateCOs(pageTemplateKey, temp2[0]); removePageTemplParams(temp2[0]); } updatePageTemplParam(updatedPTPDoc); if (newPTPs > 0) { paramKeys = createPageTemplParam(null, newPTPDoc); } } catch (VerticalRemoveException vre) { String message = "Failed to remove old page template parameters: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 3, message, vre); } catch (VerticalCreateException vce) { String message = "Failed to create new page template parameters: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 4, message, vce); } if (contentobjects != null) { // update all pageconobj entries for page try { Document cobsDoc = XMLTool.createDocument(); cobsDoc.appendChild(cobsDoc.importNode(contentobjects, true)); updatePageTemplateCOs(cobsDoc, pageTemplateKey, paramKeys); } catch (VerticalCreateException vce) { String message = "Failed to create new link from page template to content objects: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 2, message, vce); } } } } } catch (SQLException sqle) { String message = "Failed to update page template because of database error: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 5, message, sqle); } catch (NumberFormatException nfe) { String message = "Failed to parse a key field: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, nfe); } catch (VerticalCreateException vce) { String message = "Failed to create sections for page template: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, vce); } finally { close(preparedStmt); close(con); } }
From source file:org.globus.workspace.persistence.PersistenceAdapterImpl.java
public void setRootUnpropTarget(int id, String path) throws WorkspaceDatabaseException { if (this.dbTrace) { logger.trace("setRootUnpropTarget(): " + Lager.id(id) + ", path = " + path); }/*ww w . j a v a 2s. c o m*/ Connection c = null; PreparedStatement pstmt = null; try { c = getConnection(); // we need two SQL statements because unprop is known to be needed // if setting path, but unknown if clearing it if (path == null) { pstmt = c.prepareStatement(SQL_UNSET_ROOT_UNPROP_TARGET); pstmt.setNull(1, Types.VARCHAR); pstmt.setInt(2, id); } else { pstmt = c.prepareStatement(SQL_SET_ROOT_UNPROP_TARGET); pstmt.setString(1, path); pstmt.setInt(2, 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.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java
private int fillPreparedStatementFromActivity(Identity owner, ExoSocialActivity activity, PreparedStatement preparedStatement, int index) throws SQLException { preparedStatement.setString(index++, activity.getTitle()); preparedStatement.setString(index++, activity.getTitleId()); preparedStatement.setString(index++, activity.getBody()); preparedStatement.setString(index++, activity.getBodyId()); preparedStatement.setLong(index++, activity.getPostedTime()); preparedStatement.setLong(index++, activity.getUpdated().getTime()); preparedStatement.setString(index++, activity.getPosterId()); preparedStatement.setString(index++, owner.getRemoteId()); preparedStatement.setString(index++, owner.getId()); preparedStatement.setString(index++, activity.getPermaLink()); preparedStatement.setString(index++, activity.getAppId()); preparedStatement.setString(index++, activity.getExternalId()); if (activity.getPriority() == null) { preparedStatement.setNull(index++, Types.FLOAT); } else {//from w w w. ja v a 2 s . c o m preparedStatement.setFloat(index++, activity.getPriority()); } preparedStatement.setBoolean(index++, activity.isHidden()); preparedStatement.setBoolean(index++, activity.isLocked()); preparedStatement.setString(index++, StringUtils.join(activity.getLikeIdentityIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getMentionedIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getCommentedIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getReplyToId(), ",")); preparedStatement.setString(index++, null); // if (activity.getTemplateParams() != null) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream output = new ObjectOutputStream(b); output.writeObject(activity.getTemplateParams()); preparedStatement.setBinaryStream(index++, new ByteArrayInputStream(b.toByteArray())); } catch (IOException e) { LOG.debug("Failed to save templateParams of activity into database"); } } else { preparedStatement.setNull(index++, Types.BLOB); } preparedStatement.setString(index++, activity.getType()); return index; }
From source file:fll.db.Queries.java
/** * Compute the total scores for all entered performance scores. Uses both * verified and unverified scores./*from w w w . j a v a 2 s . c o m*/ * * @param connection connection to the database * @param tournament the tournament to update scores for. * @throws SQLException */ private static void updatePerformanceScoreTotals(final ChallengeDescription description, final Connection connection, final int tournament) throws SQLException { PreparedStatement updatePrep = null; PreparedStatement selectPrep = null; ResultSet rs = null; try { // build up the SQL updatePrep = connection.prepareStatement( "UPDATE Performance SET ComputedTotal = ? WHERE TeamNumber = ? AND Tournament = ? AND RunNumber = ?"); updatePrep.setInt(3, tournament); selectPrep = connection.prepareStatement("SELECT * FROM Performance WHERE Tournament = ?"); selectPrep.setInt(1, tournament); final PerformanceScoreCategory performanceElement = description.getPerformance(); final double minimumPerformanceScore = performanceElement.getMinimumScore(); rs = selectPrep.executeQuery(); while (rs.next()) { if (!rs.getBoolean("Bye")) { final int teamNumber = rs.getInt("TeamNumber"); final int runNumber = rs.getInt("RunNumber"); final TeamScore teamScore = new DatabaseTeamScore(teamNumber, runNumber, rs); final double computedTotal; if (teamScore.isNoShow()) { computedTotal = Double.NaN; } else { computedTotal = performanceElement.evaluate(teamScore); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Updating performance score for " + teamNumber + " run: " + runNumber + " total: " + computedTotal); } if (!Double.isNaN(computedTotal)) { updatePrep.setDouble(1, Math.max(computedTotal, minimumPerformanceScore)); } else { updatePrep.setNull(1, Types.DOUBLE); } updatePrep.setInt(2, teamNumber); updatePrep.setInt(4, runNumber); updatePrep.executeUpdate(); } } rs.close(); updatePrep.close(); selectPrep.close(); } finally { SQLFunctions.close(rs); SQLFunctions.close(updatePrep); SQLFunctions.close(selectPrep); } }