List of usage examples for java.sql PreparedStatement clearParameters
void clearParameters() throws SQLException;
From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java
public long getLastUpdate() { PreparedStatement segmentSelect = null; ResultSet resultSet = null;//ww w.ja va 2 s . co m Connection connection = null; try { connection = dataSource.getConnection(); segmentSelect = connection .prepareStatement("select version_ from search_segments order by version_ desc"); segmentSelect.clearParameters(); resultSet = segmentSelect.executeQuery(); if (resultSet.next()) { return resultSet.getLong(1); } else { return 0; } } catch (Exception ex) { log.warn(" Cant find last update time " + ex.getClass().getName() + ":" + ex.getMessage()); return 0; } finally { try { resultSet.close(); } catch (Exception ex) { log.debug(ex); } try { segmentSelect.close(); } catch (Exception ex) { log.debug(ex); } try { connection.close(); } catch (Exception ex) { log.debug(ex); } } }
From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java
/** * Create the xref table for seedlists used by configurations. * @param c // w w w . j av a 2s .c o m * A connection to the database * @param d * A domain to operate on. * @param dc * A configuration to create xref table for. * @throws SQLException * If any database problems occur during the insertion of * seedlist entries for the given domain configuration */ private void createConfigSeedlistsEntries(Connection c, Domain d, DomainConfiguration dc) throws SQLException { PreparedStatement s = c.prepareStatement("INSERT INTO config_seedlists " + " ( config_id, seedlist_id ) " + "SELECT configurations.config_id, seedlists.seedlist_id" + " FROM configurations, seedlists" + " WHERE configurations.name = ?" + " AND seedlists.name = ?" + " AND configurations.domain_id = ?" + " AND seedlists.domain_id = ?"); for (Iterator<SeedList> seedlists = dc.getSeedLists(); seedlists.hasNext();) { SeedList sl = seedlists.next(); s.setString(1, dc.getName()); s.setString(2, sl.getName()); s.setLong(3, d.getID()); s.setLong(4, d.getID()); s.executeUpdate(); s.clearParameters(); } }
From source file:org.apache.roller.weblogger.business.startup.DatabaseInstaller.java
/** * Upgrade database for Roller 2.0.0//from w w w . j a v a2 s. com */ private void upgradeTo200(Connection con, boolean runScripts) throws StartupException { SQLScriptRunner runner = null; try { if (runScripts) { String handle = getDatabaseHandle(con); String scriptPath = handle + "/130-to-200-migration.sql"; successMessage("Running database upgrade script: " + scriptPath); runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath)); runner.runScript(con, true); messages.addAll(runner.getMessages()); } successMessage("Doing upgrade to 200 ..."); successMessage("Populating roller_user_permissions table"); PreparedStatement websitesQuery = con .prepareStatement("select w.id as wid, u.id as uid, u.username as uname from " + "website as w, rolleruser as u where u.id=w.userid"); PreparedStatement websiteUpdate = con.prepareStatement("update website set handle=? where id=?"); PreparedStatement entryUpdate = con.prepareStatement("update weblogentry set userid=?, status=?, " + "pubtime=pubtime, updatetime=updatetime " + "where publishentry=? and websiteid=?"); PreparedStatement permsInsert = con.prepareStatement("insert into roller_permissions " + "(id, username, actions, objectid, objecttype, pending, datecreated) " + "values (?,?,?,?,?,?,?)"); // loop through websites, each has a user java.sql.Date now = new java.sql.Date(new Date().getTime()); ResultSet websiteSet = websitesQuery.executeQuery(); while (websiteSet.next()) { String websiteid = websiteSet.getString("wid"); String userid = websiteSet.getString("uid"); String username = websiteSet.getString("uname"); successMessage("Processing website: " + username); // use website user's username as website handle websiteUpdate.clearParameters(); websiteUpdate.setString(1, username); websiteUpdate.setString(2, websiteid); websiteUpdate.executeUpdate(); // update all of pubished entries to include userid and status entryUpdate.clearParameters(); entryUpdate.setString(1, userid); entryUpdate.setString(2, "PUBLISHED"); entryUpdate.setBoolean(3, true); entryUpdate.setString(4, websiteid); entryUpdate.executeUpdate(); // update all of draft entries to include userid and status entryUpdate.clearParameters(); entryUpdate.setString(1, userid); entryUpdate.setString(2, "DRAFT"); entryUpdate.setBoolean(3, false); entryUpdate.setString(4, websiteid); entryUpdate.executeUpdate(); // add permission for user in website permsInsert.clearParameters(); permsInsert.setString(1, websiteid + "p"); permsInsert.setString(2, username); permsInsert.setString(3, WeblogPermission.ADMIN); permsInsert.setString(4, websiteid); permsInsert.setString(5, "Weblog"); permsInsert.setBoolean(6, false); permsInsert.setDate(7, now); permsInsert.setBoolean(5, false); permsInsert.executeUpdate(); } if (!con.getAutoCommit()) con.commit(); successMessage("Upgrade to 200 complete."); } catch (Exception e) { log.error("ERROR running 310 database upgrade script", e); if (runner != null) messages.addAll(runner.getMessages()); errorMessage("Problem upgrading database to version 200", e); throw new StartupException("Problem upgrading database to version 200", e); } updateDatabaseVersion(con, 200); }
From source file:com.commander4j.db.JDBDespatch.java
public boolean delete() { PreparedStatement stmtupdate; boolean result = false; setErrorMessage(""); logger.debug("delete [" + getDespatchNo() + "]"); LinkedList<String> assignedList = new LinkedList<String>(); JDBPallet pal = new JDBPallet(getHostID(), getSessionID()); if (isValid(false) == true) { String journeyRef = getJourneyRef(); assignedList.clear();/*from w w w . j a va2 s . c o m*/ assignedList.addAll(getAssignedSSCCs()); if (assignedList.size() > 0) { for (int j = 0; j < assignedList.size(); j++) { if (pal.getPalletProperties(assignedList.get(j))) { pal.setDespatchNo(""); pal.update(); } } } try { stmtupdate = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement( Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBDespatch.delete")); stmtupdate.setString(1, getDespatchNo()); stmtupdate.execute(); stmtupdate.clearParameters(); Common.hostList.getHost(getHostID()).getConnection(getSessionID()).commit(); stmtupdate.close(); if (journeyRef.equals("") == false) { JDBJourney jrny = new JDBJourney(getHostID(), getSessionID()); if (jrny.getJourneyRefProperties(journeyRef)) { jrny.setStatus("Unassigned"); jrny.setDespatchNo(""); jrny.update(); } } result = true; } catch (SQLException e) { setErrorMessage(e.getMessage()); } } return result; }
From source file:org.apache.hive.jdbc.TestJdbcDriver2.java
/** * Execute non-select statements using execute() and executeUpdated() APIs * of PreparedStatement interface/*w w w . ja v a 2s .c o m*/ * @throws Exception */ @Test public void testExecutePreparedStatement() throws Exception { String key = "testKey"; String val1 = "val1"; String val2 = "val2"; PreparedStatement ps = con.prepareStatement("set " + key + " = ?"); // execute() of Prepared statement ps.setString(1, val1); ps.execute(); verifyConfValue(con, key, val1); // executeUpdate() of Prepared statement ps.clearParameters(); ps.setString(1, val2); ps.executeUpdate(); verifyConfValue(con, key, val2); }
From source file:org.apereo.portal.groups.RDBMEntityGroupStore.java
public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException { EntityIdentifier[] r = new EntityIdentifier[0]; ArrayList ar = new ArrayList(); Connection conn = null;//from www.j a va2s.c o m PreparedStatement ps = null; int type = EntityTypesLocator.getEntityTypes().getEntityIDFromType(leaftype).intValue(); //System.out.println("Checking out groups of leaftype "+leaftype.getName()+" or "+type); try { conn = RDBMServices.getConnection(); switch (method) { case IS: ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroups); break; case STARTS_WITH: query = query + "%"; ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroupsPartial); break; case ENDS_WITH: query = "%" + query; ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroupsPartial); break; case CONTAINS: query = "%" + query + "%"; ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroupsPartial); break; default: throw new GroupsException("Unknown search type"); } try { ps.clearParameters(); ps.setInt(1, type); ps.setString(2, query); ResultSet rs = ps.executeQuery(); try { //System.out.println(ps.toString()); while (rs.next()) { //System.out.println("result"); ar.add(new EntityIdentifier(rs.getString(1), ICompositeGroupService.GROUP_ENTITY_TYPE)); } } finally { close(rs); } } finally { close(ps); } } catch (Exception e) { log.error("RDBMChannelDefSearcher.searchForEntities(): " + ps, e); } finally { RDBMServices.releaseConnection(conn); } return (EntityIdentifier[]) ar.toArray(r); }
From source file:org.jasig.portal.groups.RDBMEntityGroupStore.java
public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException { EntityIdentifier[] r = new EntityIdentifier[0]; ArrayList ar = new ArrayList(); Connection conn = null;/*ww w . j av a 2 s . c o m*/ PreparedStatement ps = null; int type = EntityTypes.getEntityTypeID(leaftype).intValue(); //System.out.println("Checking out groups of leaftype "+leaftype.getName()+" or "+type); try { conn = RDBMServices.getConnection(); switch (method) { case IS: ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroups); break; case STARTS_WITH: query = query + "%"; ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroupsPartial); break; case ENDS_WITH: query = "%" + query; ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroupsPartial); break; case CONTAINS: query = "%" + query + "%"; ps = conn.prepareStatement(RDBMEntityGroupStore.searchGroupsPartial); break; default: throw new GroupsException("Unknown search type"); } try { ps.clearParameters(); ps.setInt(1, type); ps.setString(2, query); ResultSet rs = ps.executeQuery(); try { //System.out.println(ps.toString()); while (rs.next()) { //System.out.println("result"); ar.add(new EntityIdentifier(rs.getString(1), org.jasig.portal.EntityTypes.GROUP_ENTITY_TYPE)); } } finally { close(rs); } } finally { close(ps); } } catch (Exception e) { log.error("RDBMChannelDefSearcher.searchForEntities(): " + ps, e); } finally { RDBMServices.releaseConnection(conn); } return (EntityIdentifier[]) ar.toArray(r); }
From source file:dk.netarkivet.harvester.datamodel.DomainDBDAO.java
/** * Update the list of configurations for the given domain, keeping IDs where * applicable. This also builds the xref tables for passwords and seedlists * used in configurations, and so should be run after those are updated. * @param connection //from w ww .j a v a 2s. c o m * A connection to the database * @param d * A domain to update. * @throws SQLException * If any database problems occur during the update process. */ private void updateConfigurations(Connection connection, Domain d) throws SQLException { Map<String, Long> oldNames = DBUtils.selectStringLongMap(connection, "SELECT name, config_id FROM configurations " + "WHERE domain_id = ?", d.getID()); PreparedStatement s = connection.prepareStatement("UPDATE configurations SET comments = ?, " + "template_id = ( SELECT template_id FROM ordertemplates " + "WHERE name = ? ), " + "maxobjects = ?, " + "maxrate = ?, " + "maxbytes = ? " + "WHERE name = ? AND domain_id = ?"); for (Iterator<DomainConfiguration> dcs = d.getAllConfigurations(); dcs.hasNext();) { DomainConfiguration dc = dcs.next(); if (oldNames.containsKey(dc.getName())) { // Update DBUtils.setComments(s, 1, dc, Constants.MAX_COMMENT_SIZE); s.setString(2, dc.getOrderXmlName()); s.setLong(3, dc.getMaxObjects()); s.setInt(4, dc.getMaxRequestRate()); s.setLong(5, dc.getMaxBytes()); s.setString(6, dc.getName()); s.setLong(7, d.getID()); s.executeUpdate(); s.clearParameters(); dc.setID(oldNames.get(dc.getName())); oldNames.remove(dc.getName()); } else { insertConfiguration(connection, d, dc); } updateConfigPasswordsEntries(connection, d, dc); updateConfigSeedlistsEntries(connection, d, dc); } s.close(); s = connection.prepareStatement("DELETE FROM configurations " + "WHERE config_id = ?"); for (Long gone : oldNames.values()) { // Before deleting, check if this is unused. Since deletion is // rare, this is allowed to take some time to give good output String usages = DBUtils.getUsages(connection, "SELECT harvestdefinitions.name" + " FROM harvestdefinitions, harvest_configs" + " WHERE harvestdefinitions.harvest_id = " + "harvest_configs.harvest_id" + " AND harvest_configs.config_id = ?", gone, gone); if (usages != null) { String name = DBUtils.selectStringValue(connection, "SELECT name FROM configurations " + "WHERE config_id = ?", gone); String message = "Cannot delete configuration " + name + " as it is used in " + usages; log.debug(message); throw new PermissionDenied(message); } s.setLong(1, gone); s.executeUpdate(); s.clearParameters(); } }
From source file:org.sakaiproject.search.component.service.impl.SearchIndexBuilderWorkerImpl.java
public boolean getHardLock(long nodeLifetime, boolean forceLock) { String nodeID = getNodeID();/* ww w.j av a2 s . co m*/ Connection connection = null; boolean locked = false; boolean autoCommit = false; PreparedStatement selectLock = null; PreparedStatement updateLock = null; PreparedStatement insertLock = null; PreparedStatement countWork = null; ResultSet resultSet = null; Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp expiryDate = new Timestamp(now.getTime() + (10L * 60L * 1000L)); try { // I need to go direct to JDBC since its just too awful to // try and do this in Hibernate. updateNodeLock(nodeLifetime); connection = dataSource.getConnection(); autoCommit = connection.getAutoCommit(); if (autoCommit) { connection.setAutoCommit(false); } selectLock = connection.prepareStatement(SELECT_LOCK_SQL); updateLock = connection.prepareStatement(UPDATE_LOCK_SQL); insertLock = connection.prepareStatement(INSERT_LOCK_SQL); countWork = connection.prepareStatement(COUNT_WORK_SQL); SearchWriterLock swl = null; selectLock.clearParameters(); selectLock.setString(1, LOCKKEY); resultSet = selectLock.executeQuery(); if (resultSet.next()) { swl = new SearchWriterLockImpl(); swl.setId(resultSet.getString(1)); swl.setNodename(resultSet.getString(2)); swl.setLockkey(resultSet.getString(3)); swl.setExpires(resultSet.getTimestamp(4)); log.debug("GOT Lock Record " + swl.getId() + "::" + swl.getNodename() + "::" + swl.getExpires()); } resultSet.close(); resultSet = null; boolean takelock = false; if (swl == null) { log.debug("_-------------NO Lock Record"); takelock = true; } else if ("none".equals(swl.getNodename())) { takelock = true; log.debug(nodeID + "_-------------no lock"); } else if (nodeID.equals(swl.getNodename())) { takelock = true; log.debug(nodeID + "_------------matched threadid "); } else if (swl.getExpires() == null || swl.getExpires().before(now)) { takelock = true; log.debug(nodeID + "_------------thread dead "); } if (takelock) { // any work ? int nitems = 0; if (!forceLock) { countWork.clearParameters(); countWork.setInt(1, SearchBuilderItem.STATE_PENDING.intValue()); resultSet = countWork.executeQuery(); if (resultSet.next()) { nitems = resultSet.getInt(1); } resultSet.close(); resultSet = null; } if (nitems > 0 || forceLock) { try { if (swl == null) { insertLock.clearParameters(); insertLock.setString(1, nodeID); insertLock.setString(2, nodeID); insertLock.setString(3, LOCKKEY); insertLock.setTimestamp(4, expiryDate); if (insertLock.executeUpdate() == 1) { log.debug("INSERT Lock Record " + nodeID + "::" + nodeID + "::" + expiryDate); locked = true; } } else { updateLock.clearParameters(); updateLock.setString(1, nodeID); updateLock.setTimestamp(2, expiryDate); updateLock.setString(3, swl.getId()); updateLock.setString(4, swl.getNodename()); updateLock.setString(5, swl.getLockkey()); if (updateLock.executeUpdate() == 1) { log.debug("UPDATED Lock Record " + swl.getId() + "::" + nodeID + "::" + expiryDate); locked = true; } } } catch (SQLException sqlex) { locked = false; log.debug("Failed to get lock, but this is Ok ", sqlex); } } } connection.commit(); } catch (Exception ex) { if (connection != null) { try { connection.rollback(); } catch (SQLException e) { log.debug(e); } } log.error("Failed to get lock " + ex.getMessage()); locked = false; } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.debug(e); } } if (selectLock != null) { try { selectLock.close(); } catch (SQLException e) { log.debug(e); } } if (updateLock != null) { try { updateLock.close(); } catch (SQLException e) { log.debug(e); } } if (insertLock != null) { try { insertLock.close(); } catch (SQLException e) { log.debug(e); } } if (countWork != null) { try { countWork.close(); } catch (SQLException e) { log.debug(e); } } if (connection != null) { try { connection.setAutoCommit(autoCommit); } catch (SQLException e) { } try { connection.close(); log.debug("Connection Closed "); } catch (SQLException e) { log.error("Error Closing Connection ", e); } connection = null; } } return locked; }
From source file:org.sakaiproject.search.component.service.impl.SearchIndexBuilderWorkerImpl.java
public void updateNodeLock(long lifeLeft) throws SQLException { Connection connection = null; String nodeID = getNodeID();/*from w ww . j a v a2 s .co m*/ PreparedStatement updateNodeLock = null; PreparedStatement deleteExpiredNodeLock = null; PreparedStatement selectExpiredNodeLock = null; PreparedStatement insertLock = null; ResultSet resultSet = null; String threadID = Thread.currentThread().getName(); boolean savedautocommit = false; Timestamp now = new Timestamp(System.currentTimeMillis()); // a node can expire, after 2 minutes, to indicate to an admin that it // is dead // the admin can then force the Timestamp nodeExpired = new Timestamp(now.getTime() + lifeLeft); try { connection = dataSource.getConnection(); connection.setAutoCommit(false); updateNodeLock = connection.prepareStatement(UPDATE_NODE_LOCK_SQL); deleteExpiredNodeLock = connection.prepareStatement(DELETE_LOCKNODE_SQL); selectExpiredNodeLock = connection.prepareStatement(SELECT_EXPIRED_NODES_SQL); insertLock = connection.prepareStatement(INSERT_LOCK_SQL); int retries = 5; boolean updated = false; while (!updated && retries > 0) { try { try { insertLock.clearParameters(); insertLock.setString(1, "Node:" + nodeID); // id insertLock.setString(2, nodeID); // nodename insertLock.setString(3, NODE_LOCK + nodeID); // lockkey insertLock.setTimestamp(4, nodeExpired); // expires log.debug(threadID + " Doing " + INSERT_LOCK_SQL + ":{" + "Node:" + nodeID + "}{" + nodeID + "}{" + NODE_LOCK + nodeID + "}{" + nodeExpired + "}"); insertLock.executeUpdate(); } catch (SQLException ex) { updateNodeLock.clearParameters(); updateNodeLock.setTimestamp(1, nodeExpired); // expires updateNodeLock.setString(2, nodeID); // nodename updateNodeLock.setString(3, NODE_LOCK + nodeID); // lockkey log.debug(threadID + " Doing " + UPDATE_NODE_LOCK_SQL + ":{" + nodeExpired + "}{" + nodeID + "}{" + NODE_LOCK + nodeID + "}"); if (updateNodeLock.executeUpdate() != 1) { log.warn("Failed to update node heartbeat " + nodeID); } } log.debug(threadID + " Doing Commit "); connection.commit(); updated = true; } catch (SQLException e) { log.warn("Retrying ", e); try { connection.rollback(); } catch (Exception ex) { log.debug(ex); } retries--; try { Thread.sleep(100); } catch (InterruptedException ie) { log.debug(ie); } } } if (!updated) { log.error("Failed to update node lock, will try next time "); } else { log.debug("Updated Node Lock on " + nodeID + " to Expire at" + nodeExpired); } retries = 5; updated = false; while (!updated && retries > 0) { try { selectExpiredNodeLock.clearParameters(); selectExpiredNodeLock.setTimestamp(1, now); log.debug(threadID + " Doing " + SELECT_EXPIRED_NODES_SQL + ":{" + now + "}"); resultSet = selectExpiredNodeLock.executeQuery(); while (resultSet.next()) { String id = resultSet.getString(1); deleteExpiredNodeLock.clearParameters(); deleteExpiredNodeLock.setString(1, id); deleteExpiredNodeLock.execute(); connection.commit(); } log.debug(threadID + " Doing Commit"); connection.commit(); resultSet.close(); updated = true; } catch (SQLException e) { log.info("Retrying Delete Due to " + e.getMessage()); log.debug("Detailed Traceback ", e); try { resultSet.close(); } catch (Exception ex) { log.debug(ex); } try { connection.rollback(); } catch (Exception ex) { log.debug(ex); } retries--; try { Thread.sleep(100); } catch (InterruptedException ie) { log.debug(ie); } } } if (!updated) { log.warn("Failed to clear old nodes, will try next time "); } } catch (Exception ex) { log.error("Failed to register node ", ex); if (connection != null) { connection.rollback(); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.debug(e); } } if (insertLock != null) { try { insertLock.close(); } catch (SQLException e) { log.debug(e); } } if (updateNodeLock != null) { try { updateNodeLock.close(); } catch (SQLException e) { log.debug(e); } } if (selectExpiredNodeLock != null) { try { selectExpiredNodeLock.close(); } catch (SQLException e) { log.debug(e); } } if (deleteExpiredNodeLock != null) { try { deleteExpiredNodeLock.close(); } catch (SQLException e) { log.debug(e); } } if (connection != null) { try { connection.setAutoCommit(savedautocommit); connection.close(); } catch (SQLException e) { log.debug(e); } connection = null; } } }