List of usage examples for java.sql Connection rollback
void rollback() throws SQLException;
Connection
object. From source file:gridool.db.catalog.DistributionCatalog.java
@Nonnull public int[] bindTableId(@Nonnull final String[] tableNames, @Nonnull final String templateTableNamePrefix) throws GridException { final int numTableNames = tableNames.length; if (numTableNames == 0) { return new int[0]; }/*from w w w. j a va2 s . com*/ final int[] tableIds = new int[numTableNames]; Arrays.fill(tableIds, -1); final String insertQuery = "INSERT INTO \"" + partitionkeyTableName + "\"(tablename, tplprefix) VALUES(?, ?)"; final String selectQuery = "SELECT tablename, id FROM \"" + partitionkeyTableName + '"'; final ResultSetHandler rsh = new ResultSetHandler() { public Object handle(final ResultSet rs) throws SQLException { for (int i = 0; rs.next(); i++) { String tblname = rs.getString(1); int pos = ArrayUtils.indexOf(tableNames, tblname); if (pos != -1) { int key = rs.getInt(2); tableIds[pos] = key; } } return null; } }; final Object[][] params = new Object[numTableNames][]; for (int i = 0; i < numTableNames; i++) { params[i] = new Object[] { tableNames[i], templateTableNamePrefix }; } synchronized (tableIdMap) { final Connection conn = GridDbUtils.getPrimaryDbConnection(dbAccessor, false); try { JDBCUtils.batch(conn, insertQuery, params); JDBCUtils.query(conn, selectQuery, rsh); conn.commit(); } catch (SQLException e) { SQLException nexterr = e.getNextException(); if (nexterr == null) { LOG.error(e); } else { LOG.error(PrintUtils.prettyPrintStackTrace(nexterr), e); } try { conn.rollback(); } catch (SQLException rbe) { LOG.warn("Rollback failed", rbe); } throw new GridException(e); } finally { JDBCUtils.closeQuietly(conn); } for (int i = 0; i < numTableNames; i++) { String tblname = tableNames[i]; int tid = tableIds[i]; if (tid == -1) { throw new IllegalStateException("Table ID is not registered for table: " + tblname); } tableIdMap.put(tblname, tid); String templateTableName = templateTableNamePrefix + tblname; tableIdMap.put(templateTableName, tid); } } return tableIds; }
From source file:org.apache.hadoop.hive.metastore.txn.CompactionTxnHandler.java
/** * Sets the user to run as. This is for the case * where the request was generated by the user and so the worker must set this value later. * @param cq_id id of this entry in the queue * @param user user to run the jobs as/* w w w . j a v a 2 s . com*/ */ public void setRunAs(long cq_id, String user) throws MetaException { try { Connection dbConn = null; Statement stmt = null; try { dbConn = getDbConn(Connection.TRANSACTION_SERIALIZABLE); stmt = dbConn.createStatement(); String s = "update COMPACTION_QUEUE set cq_run_as = '" + user + "' where cq_id = " + cq_id; LOG.debug("Going to execute update <" + s + ">"); if (stmt.executeUpdate(s) != 1) { LOG.error("Unable to update compaction record"); LOG.debug("Going to rollback"); dbConn.rollback(); } LOG.debug("Going to commit"); dbConn.commit(); } catch (SQLException e) { LOG.error("Unable to update compaction queue, " + e.getMessage()); LOG.debug("Going to rollback"); rollbackDBConn(dbConn); checkRetryable(dbConn, e, "setRunAs(cq_id:" + cq_id + ",user:" + user + ")"); } finally { closeDbConn(dbConn); closeStmt(stmt); } } catch (RetryException e) { setRunAs(cq_id, user); } }
From source file:com.netflix.metacat.usermetadata.mysql.MysqlUserMetadataService.java
@Override public void deleteDataMetadatas(@Nonnull final List<String> uris) { try {/*from w w w . ja v a2 s . c o m*/ final Connection conn = poolingDataSource.getConnection(); try { final List<List<String>> subLists = Lists.partition(uris, config.getUserMetadataMaxInClauseItems()); for (List<String> subUris : subLists) { _deleteDataMetadatas(conn, subUris); } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } } catch (SQLException e) { log.error("Sql exception", e); throw new UserMetadataServiceException(String.format("Failed deleting the data metadata for %s", uris), e); } }
From source file:dbutils.DbUtilsTemplate.java
/** * sql?,?????/*from w ww.ja v a 2s. c o m*/ * * @param sql sql? * @param params ? * @return ?? */ public int update(String sql, Object[] params) throws SQLException { queryRunner = new QueryRunner(); int affectedRows = 0; Connection conn = null; try { conn = dataSource.getConnection(); if (params == null) { affectedRows = queryRunner.update(conn, sql); } else { affectedRows = queryRunner.update(conn, sql, params); } } catch (SQLException e) { LOG.error("Error occured while attempting to update data", e); if (conn != null) { conn.rollback(); } throw e; } finally { if (conn != null) DbUtils.commitAndClose(conn); } return affectedRows; }
From source file:edu.ncsa.sstde.indexing.postgis.PostgisIndexer.java
/** * {@inheritDoc}//from www . j a v a 2 s .c o m */ @Override public void rollback() { try { addedStatements = null; Connection conn = getConnectionInternal(); if (conn != null) conn.rollback(); } catch (SQLException e) { throw new IndexException("Rollback error", e); } }
From source file:com.netflix.metacat.usermetadata.mysql.MysqlUserMetadataService.java
@Override public void softDeleteDataMetadatas(final String user, @Nonnull final List<String> uris) { try {//from w w w. j a v a 2 s. c o m final Connection conn = poolingDataSource.getConnection(); try { final List<List<String>> subLists = Lists.partition(uris, config.getUserMetadataMaxInClauseItems()); for (List<String> subUris : subLists) { _softDeleteDataMetadatas(conn, user, subUris); } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } } catch (SQLException e) { log.error("Sql exception", e); throw new UserMetadataServiceException(String.format("Failed deleting the data metadata for %s", uris), e); } }
From source file:edu.clemson.cs.nestbed.server.adaptation.sql.MoteDeploymentConfigurationSqlAdapter.java
public MoteDeploymentConfiguration deleteMoteDeploymentConfiguration(int id) throws AdaptationException { MoteDeploymentConfiguration mdc = null; Connection connection = null; Statement statement = null;//from w ww. java 2s.c o m ResultSet resultSet = null; try { String query = "SELECT * FROM MoteDeploymentConfigurations " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { String msg = "Unable to select config to delete."; log.error(msg); throw new AdaptationException(msg); } mdc = getMoteDeploymentConfiguration(resultSet); query = "DELETE FROM MoteDeploymentConfigurations " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteMoteDeploymentConfiguration"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return mdc; }
From source file:com.netflix.metacat.usermetadata.mysql.MySqlTagService.java
@Override public Void delete(final QualifiedName name, final boolean updateUserMetadata) { try {/*from w w w .j a va 2s. c o m*/ final Connection conn = getDataSource().getConnection(); try { new QueryRunner().update(conn, SQL_DELETE_TAG_ITEM_TAGS_BY_NAME, name.toString()); new QueryRunner().update(conn, SQL_DELETE_TAG_ITEM, name.toString()); if (updateUserMetadata) { // Set the tags in user metadata final Map<String, Set<String>> data = Maps.newHashMap(); data.put(NAME_TAGS, Sets.newHashSet()); userMetadataService.saveDefinitionMetadata(name, "admin", Optional.of(metacatJson.toJsonObject(data)), true); } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } } catch (SQLException e) { final String message = String.format("Failed to delete all tags for name %s", name); log.error(message, e); throw new UserMetadataServiceException(message, e); } return null; }
From source file:gridool.db.sql.ParallelSQLExecJob.java
private static String invokeReduceDDL(final Connection conn, final String reduceQuery, final String outputTableName, final OutputMethod outputMethod, final ReadWriteLock rwlock) throws GridException { final String query; if (outputMethod == OutputMethod.view) { query = "CREATE VIEW \"" + outputTableName + "\" AS (\n" + reduceQuery + ')'; } else if (outputMethod == OutputMethod.table) { query = "CREATE TABLE \"" + outputTableName + "\" AS (\n" + reduceQuery + ") WITH DATA"; } else {/*www .j a v a 2 s . co m*/ throw new IllegalStateException("Unexpected OutputMethod: " + outputMethod); } if (LOG.isInfoEnabled()) { LOG.info("Executing a Reduce SQL query: \n" + query); } final Lock wlock = rwlock.writeLock(); try { wlock.lock(); JDBCUtils.update(conn, query); } catch (SQLException e) { String errmsg = "failed running a reduce query: " + query; LOG.error(errmsg, e); try { conn.rollback(); } catch (SQLException rbe) { LOG.warn("Rollback failed", rbe); } throw new GridException(errmsg, e); } finally { wlock.unlock(); } return outputTableName; }
From source file:fitmon.WorkoutData.java
public void addData(String workout, String intensity, int minutes, double calories, String date, int userId) throws IOException, NoSuchAlgorithmException, InvalidKeyException, JSONException, SQLException, ClassNotFoundException {/*from w ww.j a v a2 s. c o m*/ //ArrayList arr = new ArrayList(al); PreparedStatement st = null; Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/fitmon", "root", "april-23"); String query = "INSERT into workout (type,calories,date,intensity,duration,userId) values (?,?,?,?,?,?);"; st = conn.prepareStatement(query); conn.setAutoCommit(false); //st.setInt(1,7); st.setString(1, workout); st.setDouble(2, calories); st.setString(3, date); st.setString(4, intensity); st.setInt(5, minutes); st.setInt(6, userId); st.addBatch(); st.executeBatch(); conn.commit(); System.out.println("Record is inserted into workout table!"); st.close(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); conn.rollback(); } finally { if (st != null) { st.close(); } if (conn != null) { conn.close(); } } }