List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:gridool.util.jdbc.JDBCUtils.java
public static int[] batch(Connection conn, String... sqls) throws SQLException { final boolean autoCommit = conn.getAutoCommit(); if (autoCommit) { conn.setAutoCommit(false);/* w w w . ja v a 2s . c o m*/ } Statement stmt = null; int[] rows = null; try { stmt = conn.createStatement(); for (int i = 0; i < sqls.length; i++) { verboseQuery(sqls[i], (Object[]) null); stmt.addBatch(sqls[i]); } rows = stmt.executeBatch(); conn.commit(); } catch (SQLException e) { conn.rollback(); rethrow(e, sqls); } finally { close(stmt); } // change back commit mode. if (autoCommit) { conn.setAutoCommit(true); } return rows; }
From source file:gridool.util.jdbc.JDBCUtils.java
/** * Execute a batch of SQL INSERT, UPDATE, or DELETE queries. * /*from w ww. j a v a 2 s .co m*/ * @param conn The Connection to use to run the query. The caller is * responsible for closing this Connection. * @param sql The SQL to execute. * @param params An array of query replacement parameters. Each row in * this array is one set of batch replacement values. * @return The number of rows updated per statement. * @throws SQLException */ public static int[] batch(Connection conn, String sql, Object[][] params) throws SQLException { final boolean autoCommit = conn.getAutoCommit(); if (autoCommit) { conn.setAutoCommit(false); } PreparedStatement stmt = null; int[] rows = null; try { stmt = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { fillStatement(stmt, params[i]); stmt.addBatch(); } verboseQuery(sql, (Object[]) params); rows = stmt.executeBatch(); } catch (SQLException e) { rethrow(e, sql, (Object[]) params); } finally { close(stmt); } return rows; }
From source file:org.openconcerto.sql.utils.SQLUtils.java
/** * If conn is in autocommit, unset it, try to execute f, if an exception is raised rollback * otherwise commit ; finally set autocommit. Otherwise just execute f as we assume the calling * method handles transactions.//w ww.j a va2s. c o m * * @param <T> type of factory * * @param conn the connection. * @param f will be executed. * @return what f returns. * @throws SQLException if a pb occurs. */ public static <T> T executeAtomic(final Connection conn, final SQLFactory<T> f) throws SQLException { // create a transaction if we aren't in any, otherwise do nothing final boolean autoCommit = conn.getAutoCommit(); final T res; if (autoCommit) { conn.setAutoCommit(false); try { res = f.create(); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } catch (RuntimeException e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } } else { res = f.create(); } return res; }
From source file:ips1ap101.lib.core.db.util.DB.java
public static boolean commit(Connection connection) { boolean autoCommit = true; /* evita el rollback si falla el getAutoCommit */ if (connection != null) { try {//from w ww. j av a 2s . c o m if (!connection.isClosed()) { autoCommit = connection.getAutoCommit(); if (!autoCommit) { connection.commit(); } return true; } } catch (SQLException ex) { Bitacora.logFatal(ex); if (!autoCommit) { rollback(connection); } } } return false; }
From source file:com.krawler.database.DbPool.java
/** * return a connection to use for the Krawler database. * //from w w w.jav a 2 s . c o m * @param * @return * @throws ServiceException */ public static Connection getConnection() throws ServiceException { java.sql.Connection conn = null; long start = KrawlerPerf.STOPWATCH_DB_CONN.start(); try { conn = sPoolingDataSource.getConnection(); if (conn.getAutoCommit() != false) conn.setAutoCommit(false); // We want READ COMMITTED transaction isolation level for duplicate // handling code in BucketBlobStore.newBlobInfo(). conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED); } catch (SQLException e) { throw ServiceException.FAILURE("getting database connection", e); } // If the connection pool is overutilized, warn about potential leaks int numActive = sConnectionPool.getNumActive(); int maxActive = sConnectionPool.getMaxActive(); if (numActive > maxActive * 0.75) { String stackTraceMsg = "Turn on debug logging for KrawlerLog.dbconn to see stack " + "traces of connections not returned to the pool."; if (KrawlerLog.dbconn.isDebugEnabled()) { StringBuffer buf = new StringBuffer(); synchronized (sConnectionStackCounter) { Iterator i = sConnectionStackCounter.iterator(); while (i.hasNext()) { String stackTrace = (String) i.next(); int count = sConnectionStackCounter.getCount(stackTrace); if (count == 0) { i.remove(); } else { buf.append(count + " connections allocated at " + stackTrace + "\n"); } } } stackTraceMsg = buf.toString(); } KrawlerLog.dbconn.warn("Connection pool is 75% utilized. " + numActive + " connections out of a maximum of " + maxActive + " in use. " + stackTraceMsg); } if (KrawlerLog.sqltrace.isDebugEnabled() || KrawlerLog.perf.isDebugEnabled()) { // conn = new DebugConnection(conn); //TODO: uncomment later[BS] } Connection krawlerCon = new Connection(conn); // If we're debugging, update the counter with the current stack trace if (KrawlerLog.dbconn.isDebugEnabled()) { Throwable t = new Throwable(); krawlerCon.setStackTrace(t); String stackTrace = SystemUtil.getStackTrace(t); synchronized (sConnectionStackCounter) { sConnectionStackCounter.increment(stackTrace); } } KrawlerPerf.STOPWATCH_DB_CONN.stop(start); return krawlerCon; }
From source file:org.apache.torque.util.Transaction.java
/** * Commit a transaction. This method takes care of releasing the connection after the commit. In databases that do not support * transactions, it only returns the connection. * * @param con The Connection for the transaction. * * @throws TorqueException Any exceptions caught during processing will be rethrown wrapped into a TorqueException. *///from w ww.j a va2s. com public static void commit(Connection con) throws TorqueException { if (con == null) { throw new NullPointerException( "Connection object was null. " + "This could be due to a misconfiguration of the " + "DataSourceFactory. Check the logs and Torque.properties " + "to better determine the cause."); } try { if (con.getMetaData().supportsTransactions() && con.getAutoCommit() == false) { con.commit(); con.setAutoCommit(true); } } catch (SQLException e) { throw new TorqueException(e); } finally { Torque.closeConnection(con); } }
From source file:org.apache.torque.util.Transaction.java
/** * Roll back a transaction in databases that support transactions. It also releases the connection. In databases that do not * support transactions, this method will log the attempt and release the connection. * * @param con The Connection for the transaction. * * @throws TorqueException Any exceptions caught during processing will be rethrown wrapped into a TorqueException. */// ww w .jav a 2 s . c o m public static void rollback(Connection con) throws TorqueException { if (con == null) { throw new TorqueException( "Connection object was null. " + "This could be due to a misconfiguration of the " + "DataSourceFactory. Check the logs and Torque.properties " + "to better determine the cause."); } else { try { if (con.getMetaData().supportsTransactions() && con.getAutoCommit() == false) { con.rollback(); con.setAutoCommit(true); } } catch (SQLException e) { log.error("An attempt was made to rollback a transaction " + "but the database did not allow the operation to be " + "rolled back.", e); throw new TorqueException(e); } finally { Torque.closeConnection(con); } } }
From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAO.java
/** * Returns the next set of files to bre processed by the worker threads. * * @param limit number of records to be retrieved * @return list of {@link UploadedFileInfoDTO} * @throws UsagePublisherException if there is an error while getting a connection or executing the query *//*from w w w. ja va 2 s.c o m*/ public static List<UploadedFileInfoDTO> getNextFilesToProcess(int limit) throws UsagePublisherException { Connection connection = null; PreparedStatement selectStatement = null; PreparedStatement updateStatement = null; ResultSet resultSet = null; boolean autoCommitStatus = false; List<UploadedFileInfoDTO> usageFileList = new ArrayList<>(); try { connection = APIMgtDBUtil.getConnection(); autoCommitStatus = connection.getAutoCommit(); connection.setAutoCommit(false); if ((connection.getMetaData().getDriverName()).contains("Oracle")) { selectStatement = connection .prepareStatement(MicroGatewayAPIUsageConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_ORACLE); } else if (connection.getMetaData().getDatabaseProductName().contains("Microsoft")) { selectStatement = connection .prepareStatement(MicroGatewayAPIUsageConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_MSSQL); } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) { selectStatement = connection .prepareStatement(MicroGatewayAPIUsageConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_DB2); } else { selectStatement = connection .prepareStatement(MicroGatewayAPIUsageConstants.GET_NEXT_FILES_TO_PROCESS_QUERY_DEFAULT); } selectStatement.setInt(1, limit); resultSet = selectStatement.executeQuery(); while (resultSet.next()) { String tenantDomain = resultSet.getString("TENANT_DOMAIN"); String fileName = resultSet.getString("FILE_NAME"); long timeStamp = resultSet.getTimestamp("FILE_TIMESTAMP").getTime(); updateStatement = connection .prepareStatement(MicroGatewayAPIUsageConstants.UPDATE_FILE_PROCESSING_STARTED_STATUS); updateStatement.setString(1, tenantDomain); updateStatement.setString(2, fileName); updateStatement.executeUpdate(); //File content (Blob) is not stored in memory. Will retrieve one by one when processing. UploadedFileInfoDTO dto = new UploadedFileInfoDTO(tenantDomain, fileName, timeStamp); usageFileList.add(dto); if (log.isDebugEnabled()) { log.debug("Added File to list : " + dto.toString()); } } connection.commit(); } catch (SQLException e) { try { if (connection != null) { connection.rollback(); } } catch (SQLException e1) { log.error("Error occurred while rolling back getting the next files to process transaction.", e1); } throw new UsagePublisherException("Error occurred while getting the next files to process.", e); } finally { try { connection.setAutoCommit(autoCommitStatus); } catch (SQLException e) { log.warn("Failed to reset auto commit state of database connection to the previous state.", e); } APIMgtDBUtil.closeStatement(updateStatement); APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet); } return usageFileList; }
From source file:org.intermine.modelproduction.MetadataManager.java
/** * Store a (key, value) pair in the metadata table of the database * @param database the database//from ww w. ja va 2 s .c om * @param key the key * @param value the value * @throws SQLException if an error occurs */ public static void store(Database database, String key, String value) throws SQLException { Connection connection = database.getConnection(); boolean autoCommit = connection.getAutoCommit(); try { connection.setAutoCommit(true); connection.createStatement().execute("DELETE FROM " + METADATA_TABLE + " where key = '" + key + "'"); if (value != null) { connection.createStatement().execute("INSERT INTO " + METADATA_TABLE + " (key, value) " + "VALUES('" + key + "', '" + StringUtil.duplicateQuotes(value) + "')"); } } finally { connection.setAutoCommit(autoCommit); connection.close(); } }
From source file:org.intermine.sql.DatabaseUtil.java
/** * Analyse given database, perform vacuum full analyse if full parameter true. * WARNING: currently PostgreSQL specific * @param db the database to analyse// ww w . j av a 2s . c o m * @param full if true perform VACUUM FULL ANALYSE * @throws SQLException if db problem */ public static void analyse(Database db, boolean full) throws SQLException { Connection conn = db.getConnection(); boolean autoCommit = conn.getAutoCommit(); try { conn.setAutoCommit(true); Statement s = conn.createStatement(); if (full) { s.execute("VACUUM FULL ANALYSE"); } else { s.execute("ANALYSE"); } conn.setAutoCommit(autoCommit); } finally { conn.setAutoCommit(autoCommit); conn.close(); } }