List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.reydentx.core.client.MySQLClient.java
public int executeMultiQuery(List<String> listQuery) { Connection conn = borrowClient(); if (conn == null) { return (-1); }/*w ww . j av a2 s . c o m*/ try { conn.setAutoCommit(false); for (String query : listQuery) { PreparedStatement ps = conn.prepareStatement(query); ps.execute(); } conn.commit(); returnObject(conn); } catch (SQLException sqlEx) { try { _logger.error("Rollback traction because ex:" + sqlEx.getMessage(), sqlEx); conn.rollback(); // must be innoDB } catch (SQLException sqlExRollback) { _logger.error(sqlExRollback.getMessage(), sqlExRollback); } } catch (Exception ex) { _logger.error(ex.getMessage(), ex); invalidClient(conn); return (-1); } finally { try { conn.setAutoCommit(true); } catch (Exception ex) { _logger.error(ex.getMessage(), ex); } } return 0; }
From source file:eionet.cr.dao.virtuoso.VirtuosoSpoBinaryDAO.java
@Override public void delete(List<String> subjectUris) throws DAOException { // make sure the list is not null or empty if (subjectUris == null || subjectUris.isEmpty()) { return;// ww w . java2 s.c o m } // convert URIs to hashes ArrayList<Long> hashes = new ArrayList<Long>(); for (String uri : subjectUris) { hashes.add(Long.valueOf(Hashes.spoHash(uri))); } // prepare connection and the hashes comma-separated Connection conn = null; String hashesStr = "(" + Util.toCSV(hashes) + ")"; try { // do it in a transaction conn = getSQLConnection(); conn.setAutoCommit(false); // delete references from SPO_BINARY SQLUtil.executeUpdate("delete from SPO_BINARY where SUBJECT in " + hashesStr, conn); // commit the transaction conn.commit(); } catch (SQLException e) { throw new DAOException(e.getMessage(), e); } finally { SQLUtil.rollback(conn); SQLUtil.close(conn); } }
From source file:com.che.software.testato.domain.dao.jdbc.impl.ElementDAO.java
/** * Creates a procedural diagram from a testCaseId, a set of elements and a * set of transitions. If activities have been reused or not to create this * diagram./* w w w . j a v a 2s . c o m*/ * * @param testCaseId the test case id. * @param elements the set of elements. * @param transitions the set of transitions. * @throws ElementCreationDAOException if an error occurs during the * creation. */ @Override public void createDiagram(int testCaseId, List<ElementCreation> elements, List<TransitionCreation> transitions) throws ElementCreationDAOException { LOGGER.debug("createDiagram(" + testCaseId + ", " + elements.size() + " elements, " + transitions.size() + " transitions)."); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); for (ElementCreation element : elements) { Integer activityId = null, pointId = null; if (element.getType().equals(ElementCreationTypes.ACTIVITY)) { activityId = (Integer) getQueryRunner().query(connection, "SELECT activity_id::int AS activityId FROM activity WHERE label = ? ", new ScalarHandler("activityId"), new Object[] { element.getLabel() }); if (null == activityId) { getQueryRunner().update(connection, "INSERT INTO activity(activity_id, global_description, label) VALUES(nextval('activity_id_seq'), NULL, ?) ", new Object[] { element.getLabel() }); activityId = (Integer) getQueryRunner().query(connection, "SELECT activity_id::int AS activityId FROM activity WHERE label = ? ", new ScalarHandler("activityId"), new Object[] { element.getLabel() }); } } else { getQueryRunner().update(connection, "INSERT INTO point(point_id, point_type, label) VALUES(nextval('point_id_seq'), ?, ?) ", new Object[] { element.getType().name(), element.getLabel() }); pointId = (Integer) getQueryRunner().query(connection, "SELECT MAX(point_id)::int AS pointId FROM point ", new ScalarHandler("pointId")); } getQueryRunner().update(connection, "INSERT INTO element(element_id, point_id, activity_id, test_case_id) VALUES(nextval('element_id_seq')," + ((null != activityId) ? "NULL" : "?") + "," + ((null != pointId) ? "NULL" : "?") + ",?) ", (null != activityId) ? new Object[] { activityId, testCaseId } : new Object[] { pointId, testCaseId }); } List<Element> createdElements = getQueryRunner().query(connection, "SELECT element_id AS elementId, point_id AS pointId, activity_id AS activityId, test_case_id AS testCaseId, COALESCE(activity.label, point.label) AS label FROM element LEFT JOIN activity USING(activity_id) LEFT JOIN point USING(point_id) WHERE test_case_id = ? ", new BeanListHandler<Element>(Element.class), new Object[] { testCaseId }); for (TransitionCreation transition : transitions) { boolean source = false, target = false; for (Element element : createdElements) { if (element.getLabel().equalsIgnoreCase(transition.getSource())) { transition.setSourceId(element.getElementId()); source = true; } if (element.getLabel().equalsIgnoreCase(transition.getTarget())) { transition.setTargetId(element.getElementId()); target = true; } if (source && target) { break; } } getQueryRunner().update(connection, "INSERT INTO transition(transition_id, target_element, source_element, test_case_id, label) VALUES(nextval('transition_id_seq'), ?, ?, ?, ?) ", new Object[] { transition.getTargetId(), transition.getSourceId(), testCaseId, (null != transition.getLabel()) ? transition.getLabel() : "" }); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new ElementCreationDAOException(e1); } throw new ElementCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:org.koiroha.jyro.workers.crawler.Crawler.java
/** * * @param job/*ww w .ja v a2 s . co m*/ * @return * @throws WorkerException */ @Distribute(name = "crawl", params = { "url", "referer" }) public void crawl(String url, String referer) throws SQLException, JyroException { List<URI> urls = retrieveLink(url); WorkerContext context = getContext(); Connection con = Transaction.getConnection(); con.setAutoCommit(false); PreparedStatement stmt1 = con.prepareStatement( "INSERT INTO jyro_urls(scheme,host,port,path,retrieved_at,created_at) VALUES(?,?,?,?,?,?)"); PreparedStatement stmt = con.prepareStatement( "SELECT EXISTS(SELECT * FROM jyro_urls WHERE scheme=? AND host=? AND port=? AND path=?)"); for (URI uri : urls) { int port = getPort(uri); if (port < 0) { logger.debug(uri + " is not supported"); continue; } stmt.setString(1, uri.getScheme()); stmt.setString(2, uri.getHost()); stmt.setInt(3, port); stmt.setString(4, uri.getPath()); ResultSet rs = stmt.executeQuery(); rs.next(); boolean exists = rs.getBoolean(1); if (!exists) { Timestamp now = new Timestamp(System.currentTimeMillis()); stmt1.setString(1, uri.getScheme()); stmt1.setString(2, uri.getHost()); stmt1.setInt(3, port); stmt1.setString(4, uri.getPath()); stmt1.setTimestamp(5, now); stmt1.setTimestamp(6, now); stmt1.executeUpdate(); con.commit(); context.call("crawl", uri.toString()); } else { logger.info("URL " + uri + " already retrieved"); } } stmt.close(); stmt1.close(); con.commit(); return; }
From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java
@Override public void delete(long aExtendedfieldValueID) throws IOFailure { ArgumentNotValid.checkNotNull(aExtendedfieldValueID, "aExtendedfieldValueID"); Connection c = HarvestDBConnection.get(); PreparedStatement stm = null; try {/*from w w w .ja v a 2s .co m*/ c.setAutoCommit(false); stm = c.prepareStatement("DELETE FROM extendedfieldvalue " + "WHERE extendedfieldvalue_id = ?"); stm.setLong(1, aExtendedfieldValueID); stm.executeUpdate(); c.commit(); } catch (SQLException e) { String message = "SQL error deleting extendedfieldvalue for ID " + aExtendedfieldValueID + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); } finally { DBUtils.closeStatementIfOpen(stm); DBUtils.rollbackIfNeeded(c, "delete extendedfield value", aExtendedfieldValueID); HarvestDBConnection.release(c); } }
From source file:cascading.jdbc.db.DBOutputFormat.java
protected void setAutoCommit(Connection connection) { try {//from w w w . j a v a 2s. c o m connection.setAutoCommit(false); } catch (Exception exception) { throw new RuntimeException("unable to set auto commit", exception); } }
From source file:net.rrm.ehour.persistence.dbvalidator.DerbyDbValidator.java
public DdlType checkDatabaseState() { boolean databaseInState; String currentVersion;/*from w w w. java 2 s. c o m*/ DdlType ddlType; LOGGER.info("Verifying datamodel version. Minimum version: " + requiredDbVersion); Connection connection = null; try { dataSource.setCreateDatabase("create"); connection = dataSource.getConnection(); connection.setAutoCommit(false); currentVersion = getCurrentVersion(connection); databaseInState = (currentVersion != null) && currentVersion.equalsIgnoreCase(requiredDbVersion); if (databaseInState) { ddlType = DdlType.NONE; LOGGER.info("Datamodel is the required version."); } else { LOGGER.info("Datamodel of version " + currentVersion + " found. Upgrading to " + requiredDbVersion); ddlType = DdlType.ALTER_TABLE; } } catch (SQLException e) { ddlType = DdlType.CREATE_TABLE; LOGGER.info("Could not determine datamodel's version, recreating.."); } finally { dataSource.setCreateDatabase(""); try { if (connection != null) { connection.close(); } } catch (SQLException e) { // LOGGER.error("Failed to close connection", e); } } if (ddlType != DdlType.NONE) { try { createOrAlterDatamodel(dataSource, ddlType); } catch (Exception e) { LOGGER.error("Failed to create or upgrade datamodel", e); } } return ddlType; }
From source file:corner.migration.impl.DBMigrationInitializerTest.java
private void executeSQL(String... sql) { try {// w ww .j a va 2 s.c om Connection con = this.factory.getSettings().getConnectionProvider().getConnection(); if (sql != null && sql.length > 0) { boolean oldAutoCommit = con.getAutoCommit(); if (!oldAutoCommit) { con.setAutoCommit(true); } try { Statement stmt = con.createStatement(); try { for (int i = 0; i < sql.length; i++) { executeSchemaStatement(stmt, sql[i]); } } finally { JdbcUtils.closeStatement(stmt); } } finally { if (!oldAutoCommit) { con.setAutoCommit(false); } } } } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:com.migratebird.database.impl.DefaultSQLHandler.java
/** * Starts a transaction by turning of auto commit. * Make sure to call endTransaction at the end of the transaction * * @param dataSource The data source, not null *//*from w w w . j av a 2s .c o m*/ public void startTransaction(DataSource dataSource) { Connection connection = getConnection(dataSource); try { if (connection.getAutoCommit()) { connection.setAutoCommit(false); } } catch (Exception e) { throw new DatabaseException("Unable to start transaction.", e); } }
From source file:com.devwebsphere.jdbc.loader.JDBCTxCallback.java
/** * This is called by Loaders to get a Data instance when they need it. The TxCallbacks job is to make one and store a reference * to it in the slot for all Loaders used in this transaction to share. * @param tx// www .ja v a2 s. c o m * @return */ public Connection getConnection(TxID tx) throws SQLException { // is there already a JDBC Connection for this transaction? Connection c = (Connection) tx.getSlot(dataSlot); if (c == null) { // create one if needed c = getDataSource().getConnection(); c.setAutoCommit(false); // store in the Tx slot for the Loaders to reuse for this transaction in the future tx.putSlot(dataSlot, c); } return c; }