List of usage examples for java.sql Connection rollback
void rollback() throws SQLException;
Connection
object. From source file:edu.lternet.pasta.dml.database.SimpleDatabaseLoader.java
/** * /*from www . j av a 2 s . co m*/ */ public void run() { if (entity == null) { success = false; completed = true; return; } //don't reload data if we have it if (doesDataExist(entity.getEntityIdentifier())) { return; } AttributeList attributeList = entity.getAttributeList(); String tableName = entity.getDBTableName(); String insertSQL = ""; Vector rowVector = new Vector(); Connection connection = null; try { rowVector = this.dataReader.getOneRowDataVector(); connection = DataManager.getConnection(); if (connection == null) { success = false; exception = new Exception("The connection to db is null"); completed = true; return; } connection.setAutoCommit(false); while (!rowVector.isEmpty()) { insertSQL = databaseAdapter.generateInsertSQL(attributeList, tableName, rowVector); if (insertSQL != null) { PreparedStatement statement = connection.prepareStatement(insertSQL); statement.execute(); } rowVector = this.dataReader.getOneRowDataVector(); } connection.commit(); success = true; } catch (Exception e) { log.error("problem while loading data into table. Error message: " + e.getMessage()); e.printStackTrace(); log.error("SQL string to insert row:\n" + insertSQL); success = false; exception = e; try { connection.rollback(); } catch (Exception ee) { System.err.println(ee.getMessage()); } } finally { try { connection.setAutoCommit(true); } catch (Exception ee) { log.error(ee.getMessage()); } DataManager.returnConnection(connection); } }
From source file:org.alinous.plugin.derby.DerbyDataSource.java
public void commit(Object connectionHandle, boolean lastAutoCommit, String trxIdentifier) throws DataSourceException { Connection con = (Connection) connectionHandle; Statement batchStmt = this.batchedStatementMap.get(con); if (batchStmt != null) { try {/*from ww w . ja va 2 s. com*/ batchStmt.executeBatch(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } try { con.setAutoCommit(lastAutoCommit); } catch (SQLException ignore) { } try { batchStmt.close(); } catch (SQLException e1) { } // this.batchStmt = null; this.batchedStatementMap.remove(con); throw new DataSourceException(e); } } try { con.commit(); } catch (SQLException e) { throw new DataSourceException(e); } finally { try { batchStmt.close(); } catch (SQLException e1) { } try { con.setAutoCommit(lastAutoCommit); } catch (SQLException ignore) { } this.batchedStatementMap.remove(con); } }
From source file:com.rosy.bill.dao.hibernate.SimpleHibernateDao.java
@SuppressWarnings("deprecation") public String callProc(final String proc, final List<Object> paramList, final int outIndex, final int outType) { String result = null;//from w w w .j a v a 2 s. c o m java.sql.Connection conn = null; java.sql.CallableStatement cstmt = null; //Session session = this.getSession(); try { conn = this.getSession().connection(); conn.setAutoCommit(false); cstmt = conn.prepareCall(proc); for (int i = 0; paramList != null && i < paramList.size(); i++) { if (i + 1 == outIndex) { //cstmt.setInt(i + 1, // (Integer.parseInt(paramList.get(i).toString()))); cstmt.setString(i + 1, paramList.get(i).toString()); } else { cstmt.setInt(i + 1, Integer.valueOf(paramList.get(i).toString())); } } cstmt.registerOutParameter(outIndex, outType); cstmt.execute(); result = cstmt.getString(outIndex); conn.commit(); //session.flush(); //session.clear(); } catch (Exception ex) { try { conn.rollback(); } catch (SQLException e1) { logger.error("[" + proc + "]?" + e1.getMessage()); e1.printStackTrace(); } ex.printStackTrace(); } finally { if (cstmt != null) { try { cstmt.close(); } catch (Exception ex) { } } } return result; }
From source file:org.apache.eagle.storage.jdbc.entity.impl.JdbcEntityUpdaterImpl.java
@Override public int update(List<E> entities) throws Exception { ConnectionManager cm = ConnectionManagerFactory.getInstance(); TorqueStatementPeerImpl<E> peer = cm.getStatementExecutor(this.jdbcEntityDefinition.getJdbcTableName()); Connection connection = cm.getConnection(); connection.setAutoCommit(false);/*ww w . ja v a2 s. c o m*/ StopWatch stopWatch = new StopWatch(); stopWatch.start(); int num = 0; try { for (E entity : entities) { String primaryKey = entity.getEncodedRowkey(); if (primaryKey == null) { primaryKey = ConnectionManagerFactory.getInstance().getStatementExecutor() .getPrimaryKeyBuilder().build(entity); entity.setEncodedRowkey(primaryKey); } PrimaryKeyCriteriaBuilder pkBuilder = new PrimaryKeyCriteriaBuilder( Collections.singletonList(primaryKey), this.jdbcEntityDefinition.getJdbcTableName()); Criteria selectCriteria = pkBuilder.build(); if (LOG.isDebugEnabled()) LOG.debug("Updating by query: " + SqlBuilder.buildQuery(selectCriteria).getDisplayString()); ColumnValues columnValues = JdbcEntitySerDeserHelper.buildColumnValues(entity, this.jdbcEntityDefinition); num += peer.delegate().doUpdate(selectCriteria, columnValues, connection); } if (LOG.isDebugEnabled()) LOG.debug("Committing updates"); connection.commit(); } catch (Exception ex) { LOG.error("Failed to update, rolling back", ex); connection.rollback(); throw ex; } finally { stopWatch.stop(); if (LOG.isDebugEnabled()) LOG.debug("Closing connection"); connection.close(); } LOG.info(String.format("Updated %s records in %s ms", num, stopWatch.getTime())); return num; }
From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java
/** * @see edu.uga.cs.fluxbuster.db.DBInterface#executeQueryWithResult(java.lang.String) *///from www. j av a 2s.co m @Override public ResultSet executeQueryWithResult(String query) { ResultSet retval = null; Connection con = null; Statement stmt = null; try { con = this.getConnection(); con.setAutoCommit(false); stmt = con.createStatement(); retval = stmt.executeQuery(query); con.commit(); } catch (SQLException e) { retval = null; if (log.isErrorEnabled()) { log.error(query, e); } try { if (con != null && !con.isClosed()) { con.rollback(); } } catch (SQLException e1) { if (log.isErrorEnabled()) { log.error("Error during rollback.", e1); } } } finally { try { if (con != null && !con.isClosed()) { con.setAutoCommit(true); con.close(); } } catch (SQLException e) { if (log.isErrorEnabled()) { log.error("Error during close.", e); } } } return retval; }
From source file:com.che.software.testato.domain.dao.jdbc.impl.ActivityDAO.java
/** * Creates the documentation of an activity from actions and parameters * lists./*from w ww . j a v a 2 s .c o m*/ * * @author Clement HELIOU (clement.heliou@che-software.com). * @param activity the activity to document. * @param actions the actions list. * @param parameters the parameters list. * @since July, 2011. * @throws ActivityDocumentationCreationDAOException if an error occurs * during the creation. */ @Override public void createActivityDocumentation(Activity activity, List<ActivityAction> actions, List<ActivityParameter> parameters) throws ActivityDocumentationCreationDAOException { LOGGER.debug("createActivityDocumentation(" + activity.getActivityId() + "," + actions.size() + " actions," + parameters.size() + " parameters)."); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); getQueryRunner().update(connection, "UPDATE activity SET global_description = ? WHERE activity_id = ? ", new Object[] { activity.getGlobalDescription(), activity.getActivityId() }); int cpt = 1; for (ActivityAction action : actions) { getQueryRunner().update(connection, "INSERT INTO activity_action(activity_action_id, activity_id, description, result, \"order\") VALUES(nextval('activity_action_id_seq'),?,?,?,?) ", new Object[] { activity.getActivityId(), action.getDescription(), action.getResult(), cpt++ }); } for (ActivityParameter parameter : parameters) { getQueryRunner().update(connection, "INSERT INTO activity_parameter(activity_parameter_id, activity_id, name, description) VALUES(nextval('activity_parameter_id_seq'),?,?,?) ", new Object[] { activity.getActivityId(), "{" + parameter.getName() + "}", parameter.getDescription() }); } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new ActivityDocumentationCreationDAOException(e1); } throw new ActivityDocumentationCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:org.alinous.plugin.mysql.MySQLDataSource.java
public void rollback(Object connectionHandle, boolean lastAutoCommit, String trxIdentifier) throws DataSourceException { Connection con = (Connection) connectionHandle; /*/* w w w .j a v a 2s . co m*/ Statement batchStmt = this.batchedStatementMap.get(con); if(batchStmt != null){ try { batchStmt.close(); } catch (SQLException e) {} //this.batchStmt = null; this.batchedStatementMap.remove(con); } */ try { con.rollback(); } catch (SQLException e) { throw new DataSourceException(e); } finally { try { con.setAutoCommit(lastAutoCommit); } catch (SQLException ignore) { } } }
From source file:org.alinous.plugin.derby.DerbyDataSource.java
public void rollback(Object connectionHandle, boolean lastAutoCommit, String trxIdentifier) throws DataSourceException { if (trxIdentifier != null) { return;//from w w w.j a va2 s. com } Connection con = (Connection) connectionHandle; Statement batchStmt = this.batchedStatementMap.get(con); if (batchStmt != null) { try { batchStmt.close(); } catch (SQLException e) { } // this.batchStmt = null; this.batchedStatementMap.remove(con); } try { con.rollback(); } catch (SQLException e) { throw new DataSourceException(e); } finally { try { con.setAutoCommit(lastAutoCommit); } catch (SQLException ignore) { } } }
From source file:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java
/** * Execute query with no result.//from www .j av a 2 s . c om * * @param query the query * @param giveException throws any exception generated if true, * if false all exceptions are consumed * @throws Exception if giveException is true and their is an error executing * the query */ public void executeQueryNoResult(String query, boolean giveException) throws Exception { Connection con = null; Statement stmt = null; SQLException exc = null; try { con = this.getConnection(); con.setAutoCommit(false); stmt = con.createStatement(); stmt.execute(query); con.commit(); } catch (SQLException e) { if (!giveException) { if (log.isErrorEnabled()) { log.error(query, e); } } if (con != null) { try { con.rollback(); } catch (SQLException e1) { if (log.isErrorEnabled()) { log.error("Error during rollback.", e1); } } } if (giveException) { exc = e; } } finally { try { if (con != null && !con.isClosed()) { con.setAutoCommit(true); con.close(); } } catch (SQLException e) { if (log.isErrorEnabled()) { log.error("Error during close.", e); } } if (exc != null && giveException) { throw exc; } } }
From source file:org.apache.cocoon.acting.DatabaseAddAction.java
/** * Add a record to the database. This action assumes that * the file referenced by the "descriptor" parameter conforms * to the AbstractDatabaseAction specifications. *///from www. j a v a 2 s .co m public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters param) throws Exception { DataSourceComponent datasource = null; Connection conn = null; Map results = new HashMap(); // read global parameter settings boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT; if (this.settings.containsKey("reloadable")) reloadable = Boolean.valueOf((String) this.settings.get("reloadable")).booleanValue(); // read local parameter settings try { Configuration conf = this.getConfiguration( param.getParameter("descriptor", (String) this.settings.get("descriptor")), resolver, param.getParameterAsBoolean("reloadable", reloadable)); datasource = this.getDataSource(conf); conn = datasource.getConnection(); Request request = ObjectModelHelper.getRequest(objectModel); if (conn.getAutoCommit()) { conn.setAutoCommit(false); } Configuration[] tables = conf.getChildren("table"); for (int i = 0; i < tables.length; i++) { Configuration table = tables[i]; processTable(table, conn, request, results); } conn.commit(); } catch (Exception e) { if (conn != null) { try { conn.rollback(); } catch (SQLException se) { getLogger().debug("There was an error rolling back the transaction", se); } } //throw new ProcessingException("Could not add record :position = " + currentIndex, e); throw new ProcessingException("Could not add record", e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException sqe) { getLogger().warn("There was an error closing the datasource", sqe); } } if (datasource != null) this.dbselector.release(datasource); } return Collections.unmodifiableMap(results); }