List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.concursive.connect.web.modules.productcatalog.beans.OrderBean.java
/** * Description of the Method/*from w w w .j a v a2 s . c om*/ * * @param db Description of the Parameter * @return Description of the Return Value * @throws SQLException Description of the Exception */ public boolean insert(Connection db) throws SQLException { try { db.setAutoCommit(false); // Insert the base order PreparedStatement pst = db.prepareStatement("INSERT INTO customer_order " + "(ipaddress, browser, total_price, order_by) VALUES (?,?,?,?) "); int i = 0; pst.setString(++i, ipAddress); pst.setString(++i, browser); pst.setDouble(++i, productList.getTotalPrice()); DatabaseUtils.setInt(pst, ++i, userId); pst.execute(); pst.close(); id = DatabaseUtils.getCurrVal(db, "customer_order_order_id_seq", -1); // Insert the products productList.setOrderId(id); productList.insert(db); // Insert the contact info if (contactInformation.isValid()) { contactInformation.setOrderId(id); contactInformation.insert(db); } // Insert the addresses if (billing.isValid()) { billing.setOrderId(id); billing.insert(db); } if (shipping.isValid()) { shipping.setOrderId(id); shipping.insert(db); } // Insert the payment info if (payment.isValid()) { payment.setOrderId(id); payment.setChargeAmount(getChargeAmount()); payment.insert(db); } db.commit(); // Finalize saved = true; return true; } catch (Exception e) { db.rollback(); LOG.error("insert", e); throw new SQLException("Could not save"); } finally { db.setAutoCommit(true); } }
From source file:com.noelios.restlet.ext.jdbc.JdbcClientHelper.java
/** * Helper/*from ww w. j a va 2s.c om*/ * * @param connection * @param returnGeneratedKeys * @param sqlRequests * @return the result of the last executed SQL request */ private JdbcResult handleSqlRequests(Connection connection, boolean returnGeneratedKeys, List<String> sqlRequests) { JdbcResult result = null; try { connection.setAutoCommit(true); final Statement statement = connection.createStatement(); for (final String sqlRequest : sqlRequests) { statement.execute(sqlRequest, returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); result = new JdbcResult(statement); } // Commit any changes to the database if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException se) { getLogger().log(Level.WARNING, "Error while processing the SQL requests", se); try { if (!connection.getAutoCommit()) { connection.rollback(); } } catch (SQLException se2) { getLogger().log(Level.WARNING, "Error while rollbacking the transaction", se); } } return result; }
From source file:mercury.DigitalMediaDAO.java
public final DigitalMediaDTO getDigitalMedia(int id, String fileName) { Connection con = null; byte[] blob = null; DigitalMediaDTO dto = new DigitalMediaDTO(); try {// w w w . j av a 2 s.c om con = getDataSource().getConnection(); String sql = " SELECT file, file_name, mime_type FROM digital_media " + " WHERE id = ? " + " AND file_name = ? ;"; PreparedStatement pst = con.prepareStatement(sql); pst.setInt(1, id); pst.setString(2, fileName); con.setAutoCommit(false); ResultSet rs = pst.executeQuery(); if (rs.next()) { blob = rs.getBytes(1); if (blob == null) { return null; } dto.setIn(new ByteArrayInputStream(blob)); dto.setLength((int) blob.length); dto.setFileName(rs.getString(2)); dto.setMimeType(rs.getString(3)); } return dto; } catch (Exception e) { log.error(e.getMessage(), e); throw new DAOException(e.getMessage()); } finally { closeConnection(con); } }
From source file:org.opencron.server.dao.HibernateDao.java
@Transactional(readOnly = false) public void executeBatch(final String[] sqlList) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setAutoCommit(false); Statement stmt = connection.createStatement(); for (String sql : sqlList) { stmt.addBatch(sql);//from ww w . j a v a 2 s . c o m } stmt.executeBatch(); connection.commit(); } }); }
From source file:hoot.services.db.DbUtils.java
public static void deleteOSMRecord(Connection conn, Long mapId) throws Exception { try {//from www .j a va2s. c o m deleteMapRelatedTablesByMapId(mapId); conn.setAutoCommit(false); Configuration configuration = getConfiguration(); QMaps maps = QMaps.maps; new SQLDeleteClause(conn, configuration, maps).where(maps.id.eq(mapId)).execute(); QReviewItems reviewItems = QReviewItems.reviewItems; new SQLDeleteClause(conn, configuration, reviewItems).where(reviewItems.mapId.eq(mapId)).execute(); QElementIdMappings elementIdMappings = QElementIdMappings.elementIdMappings; new SQLDeleteClause(conn, configuration, elementIdMappings).where(elementIdMappings.mapId.eq(mapId)) .execute(); QReviewMap reviewMap = QReviewMap.reviewMap; new SQLDeleteClause(conn, configuration, reviewMap).where(reviewMap.mapId.eq(mapId)).execute(); conn.commit(); } catch (Exception e) { String msg = "Error deleting OSM record. "; msg += " " + e.getCause().getMessage(); throw new Exception(msg); } finally { conn.setAutoCommit(true); } }
From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java
/** * Insert text into PostgreSQL//from w w w.ja v a 2 s . c o m * * @param files * List of Strings of text to insert * * @return number of rows affected * * @throws Exception TODO describe exception */ public int addFile(String action_number, String make, String model, String year, String compname, String mfr_name, String odate, String cdate, String campno, String subject, String summary) throws Exception { String sql = "INSERT INTO reportedErrors (action_number, make, model, year, compname, mfr_name, odate, cdate, campno, subject, summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,)"; Connection connection = null; PreparedStatement statement = null; try { connection = getConnection(); connection.setAutoCommit(false); statement = connection.prepareStatement(sql); statement.setString(1, action_number); statement.setString(2, make); statement.setString(3, model); statement.setString(4, year); statement.setString(5, compname); statement.setString(6, mfr_name); statement.setString(7, odate); statement.setString(8, cdate); statement.setString(9, campno); statement.setString(10, subject); statement.setString(11, summary); statement.addBatch(); int[] rows = statement.executeBatch(); connection.commit(); return rows.length; } catch (SQLException e) { SQLException next = e.getNextException(); if (next != null) { throw next; } throw e; } finally { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } }
From source file:org.opencron.server.dao.HibernateDao.java
@Transactional(readOnly = false) public void executeBatch(final String sql, final Object[]... parameters) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setAutoCommit(false); PreparedStatement stmt = connection.prepareStatement(sql); for (Object[] arr : parameters) { int i = 1; for (Object p : arr) { stmt.setObject(i++, p); }// w w w . j a v a 2s.c o m stmt.addBatch(); } stmt.executeBatch(); connection.commit(); } }); }
From source file:com.che.software.testato.domain.dao.jdbc.impl.IterationDAO.java
/** * Creates the next iteration (both analytical and selective) for a given * prioritization./* w ww . j a va2s . c om*/ * * @author Clement HELIOU (clement.heliou@che-software.com). * @param prioritization the given prioritization. * @param scripts the scripts to use for this depth. * @since July, 2011. * @throws IterationCreationDAOException if an error occurs during the * creation. */ @Override public void createNextIteration(Prioritization prioritization, List<Script> scripts) throws IterationCreationDAOException { LOGGER.debug("createNextIteration(" + prioritization.getPrioritizationId() + ")."); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); getQueryRunner().update(connection, "INSERT INTO iteration(iteration_id, prioritization_id) VALUES(nextval('iteration_seq'), ?) ", new Object[] { prioritization.getPrioritizationId() }); Integer createdIterationId = (Integer) getQueryRunner().query(connection, "SELECT MAX(iteration_id)::int AS iterationId FROM iteration ", new ScalarHandler("iterationId")); getQueryRunner().update(connection, "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ", new Object[] { CriterionTypes.COST.name(), createdIterationId, AssignmentStatus.NOT_ASSIGNED.name() }); createComparisonMatrixItem(connection, scripts, (Integer) getQueryRunner().query(connection, "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ", new ScalarHandler("result"))); getQueryRunner().update(connection, "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ", new Object[] { CriterionTypes.FIT.name(), createdIterationId, AssignmentStatus.NOT_ASSIGNED.name() }); createComparisonMatrixItem(connection, scripts, (Integer) getQueryRunner().query(connection, "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ", new ScalarHandler("result"))); getQueryRunner().update(connection, "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ", new Object[] { CriterionTypes.RISK.name(), createdIterationId, AssignmentStatus.NOT_ASSIGNED.name() }); createComparisonMatrixItem(connection, scripts, (Integer) getQueryRunner().query(connection, "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ", new ScalarHandler("result"))); getQueryRunner().update(connection, "INSERT INTO iteration_assignment(iteration_assignment_id, criterion_type, iteration_id, analytical_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?, ?) ", new Object[] { CriterionTypes.VALUE.name(), createdIterationId, AssignmentStatus.NOT_ASSIGNED.name() }); createComparisonMatrixItem(connection, scripts, (Integer) getQueryRunner().query(connection, "SELECT MAX(iteration_assignment_id)::int AS result FROM iteration_assignment ", new ScalarHandler("result"))); getQueryRunner().update(connection, "INSERT INTO iteration_assignment(iteration_assignment_id, iteration_id, selective_prioritization_status) VALUES(nextval('iteration_assignment_seq'), ?, ?) ", new Object[] { createdIterationId, AssignmentStatus.NOT_ASSIGNED.name() }); connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new IterationCreationDAOException(e1); } throw new IterationCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:org.killbill.bus.TestPersistentBusDemo.java
@Test(groups = "slow") public void testDemo() throws SQLException, PersistentBus.EventBusException { // Create a Handler (with @Subscribe method) final DummyHandler handler = new DummyHandler(); bus.register(handler);/*from ww w. j ava 2 s.c om*/ // Extract connection from dataSource final Connection connection = dataSource.getConnection(); final DummyEvent event = new DummyEvent("foo", 1L, 2L, UUID.randomUUID()); PreparedStatement stmt = null; try { // In one transaction we both insert a dummy value in some table, and post the event (using same connection/transaction) connection.setAutoCommit(false); stmt = connection.prepareStatement("insert into dummy (dkey, dvalue) values (?, ?)"); stmt.setString(1, "Great!"); stmt.setLong(2, 47L); stmt.executeUpdate(); bus.postFromTransaction(event, connection); connection.commit(); } finally { if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } // // Verify we see the dummy value inserted and also received the event posted // final Connection connection2 = dataSource.getConnection(); PreparedStatement stmt2 = null; try { stmt2 = connection2.prepareStatement("select * from dummy where dkey = ?"); stmt2.setString(1, "Great!"); final ResultSet rs2 = stmt2.executeQuery(); int found = 0; while (rs2.next()) { found++; } Assert.assertEquals(found, 1); } finally { stmt2.close(); } if (connection2 != null) { connection2.close(); } Assert.assertTrue(handler.waitForCompletion(1, 3000)); }
From source file:com.zimbra.cs.db.SQLite.java
@Override void postCreate(Connection conn) throws SQLException { try {// w ww. java2 s . c o m conn.setAutoCommit(true); pragmas(conn, null); } finally { conn.setAutoCommit(false); } }