List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:org.rimudb.storedproc.StoredProcedure.java
public List execute(boolean autoCommit) throws RimuDBException { ArrayList resultList = null;/*from w ww . j a v a 2 s . c o m*/ Connection conn = null; int statID = 0; CallableStatement stmt = null; boolean originalAutoCommit = false; try { // Get a connection conn = database.getDatabaseConnection(); originalAutoCommit = conn.getAutoCommit(); conn.setAutoCommit(autoCommit); String sql = createSQL(); // Get the statistic ID int loggingType = database.getDatabaseConfiguration().getLoggingType(); if (loggingType == DatabaseConfiguration.LOG_STATISTICS) { statID = StatisticCollector.getInstance().createStatistic(sql); } else if (loggingType == DatabaseConfiguration.LOG_SQL_ONLY) { log.info("SQL=" + sql); } // Prepare the call stmt = conn.prepareCall(sql); int parameterCount = 0; if (getReturnType() != NONE) { parameterCount++; stmt.registerOutParameter(parameterCount, getReturnType()); } // Assign parameters for (int i = 0; i < parameterList.size(); i++) { parameterCount++; // If the parameter is an IN type parameter then if (parameterList.get(i) instanceof StoredProcINParameter || parameterList.get(i) instanceof StoredProcINOUTParameter) { stmt.setObject(parameterCount, parameterList.get(i).getValue()); } // If the parameter is an OUT type if (parameterList.get(i) instanceof StoredProcOUTParameter) { stmt.registerOutParameter(parameterCount, ((StoredProcOUTParameter) parameterList.get(i)).getSqlType()); } // If the parameter is an INOUT type if (parameterList.get(i) instanceof StoredProcINOUTParameter) { stmt.registerOutParameter(parameterCount, ((StoredProcINOUTParameter) parameterList.get(i)).getSqlType()); } } if (statID > 0) StatisticCollector.getInstance().logEvent(statID, "preparetime"); // Execute the call boolean result = stmt.execute(); if (statID > 0) StatisticCollector.getInstance().logEvent(statID, "executetime"); // If we got a result set if (result) { // Create the empty list to contain the rows resultList = new ArrayList(); // While there is a result set to be retrieved while (result) { // Get the result set ResultSet rs = stmt.getResultSet(); // Process the result set List list = processResultSet(rs); // And close the result set rs.close(); // Add the result set to the full list if (list != null) { resultList.addAll(list); } // Check for more results result = stmt.getMoreResults(); } } // If there was a return value if (getReturnType() != NONE) { Object value = stmt.getObject(1); if (value instanceof ResultSet) { resultList = new ArrayList(); ResultSet rs = (ResultSet) value; List list = processResultSet(rs); rs.close(); if (list != null) { resultList.addAll(list); } } else { returnValue = value; } } // Assign the out values for (int i = 0; i < parameterList.size(); i++) { // If the parameter is an OUT type if (parameterList.get(i) instanceof StoredProcOUTParameter || parameterList.get(i) instanceof StoredProcINOUTParameter) { Object value = stmt.getObject(i + 1); // Don't save ResultSets in the parameters if (!(value instanceof ResultSet)) { parameterList.get(i).setValue(value); } } } if (statID > 0) { StatisticCollector.getInstance().logEvent(statID, "processtime"); if (StatisticCollector.getInstance().exceedsThreshold(statID, database.getDatabaseConfiguration().getLoggingThreshold())) { String text = StatisticCollector.getInstance().formatStatistics(statID, database.getStatisticFormatter()); log.info(text); } StatisticCollector.getInstance().removeID(statID); } return resultList; } catch (SQLException e) { throw new RimuDBException(e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // Don't care about a failure here } } if (conn != null) { try { conn.setAutoCommit(originalAutoCommit); conn.close(); } catch (SQLException e) { // Don't care about a failure here } } } }
From source file:org.sakaiproject.announcement.impl.DbAnnouncementService.java
/** * fill in the pubview db fields//from w w w . j a v a2 s. c om */ protected void convertToPubView() { M_log.info("convertToPubView"); try { // get a connection final Connection connection = m_sqlService.borrowConnection(); boolean wasCommit = connection.getAutoCommit(); connection.setAutoCommit(false); // read all message records that need conversion String sql = "select CHANNEL_ID, MESSAGE_ID, XML, PUBVIEW from " + m_rTableName; m_sqlService.dbRead(connection, sql, null, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { // create the Resource from the db xml String channelId = result.getString(1); String messageId = result.getString(2); String xml = result.getString(3); String pubViewSetting = result.getString(4); // read the xml Document doc = Xml.readDocumentFromString(xml); // verify the root element Element root = doc.getDocumentElement(); if (!root.getTagName().equals("message")) { M_log.warn("convertToPubView(): XML root element not message: " + root.getTagName()); return null; } BaseMessageEdit m = new BaseMessageEdit(null, root); // check if the record already has pub view set in the properties boolean pubview = false; if (m.getProperties().getProperty(ResourceProperties.PROP_PUBVIEW) != null) { // pub view set in properties and in db indicates all is well with this one if ("1".equals(pubViewSetting)) { return null; } // having the property overrides any realm setting... pubview = true; } // if we don't know pubview from the props, check the realm else { // m.getReference() won't work cause we didn't give it its channel... Reference channel = m_entityManager.newReference(channelId); String ref = messageReference(channel.getContext(), channel.getId(), m.getId()); pubview = getPubView(ref); // if the pubview setting matches the db, and it's false, all is well if ((!pubview) && ("0".equals(pubViewSetting))) { return null; } } // update those that have no pubview if (!pubview) { String update = "update " + m_rTableName + " set PUBVIEW = ? where CHANNEL_ID = ? and MESSAGE_ID = ?"; Object fields[] = new Object[3]; fields[0] = "0"; fields[1] = channelId; fields[2] = messageId; boolean ok = m_sqlService.dbWrite(connection, update, fields); if (!ok) M_log.info("convertToPubView: channel: " + channelId + " message: " + messageId + " pubview: " + pubview + " ok: " + ok); } // update those that have pubview else { // set the property m.getPropertiesEdit().addProperty(ResourceProperties.PROP_PUBVIEW, Boolean.TRUE.toString()); // form updated XML doc = Xml.createDocument(); m.toXml(doc, new Stack()); xml = Xml.writeDocumentToString(doc); String update = "update " + m_rTableName + " set PUBVIEW = ?, XML = ? where CHANNEL_ID = ? and MESSAGE_ID = ?"; Object fields[] = new Object[4]; fields[0] = "1"; fields[1] = xml; fields[2] = channelId; fields[3] = messageId; boolean ok = m_sqlService.dbWrite(connection, update, fields); if (!ok) M_log.info("convertToPubView: channel: " + channelId + " message: " + messageId + " pubview: " + pubview + " ok: " + ok); } return null; } catch (Throwable ignore) { return null; } } }); connection.commit(); connection.setAutoCommit(wasCommit); m_sqlService.returnConnection(connection); } catch (Throwable t) { M_log.warn("convertToPubView: failed: " + t); } M_log.info("convertToPubView: done"); }
From source file:com.asakusafw.testdriver.TestDriverTestToolsBase.java
private void updateTimestamp(String tableName, String timestampColumn, Timestamp timestamp) { LOG.info("{}?{}??????", tableName, timestampColumn); Connection conn = null; PreparedStatement stmt = null; try {/*from w w w . j a va 2s.co m*/ conn = DbUtils.getConnection(); stmt = conn.prepareStatement( MessageFormat.format("UPDATE {0} SET {1} = ? WHERE {1} IS NULL", tableName, timestampColumn)); stmt.setTimestamp(1, timestamp); int rows = stmt.executeUpdate(); LOG.info("{}?{}?????: {}", new Object[] { tableName, timestampColumn, rows }); if (conn.getAutoCommit() == false) { conn.commit(); } } catch (SQLException e) { e.printStackTrace(); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(conn); } }
From source file:com.adaptris.core.jdbc.DatabaseConnection.java
/** * <p>/*from ww w .j av a 2s. c o m*/ * Initiate a connection to the database. * </p> * * @throws SQLException if connection fails after exhausting the specified number of retry attempts */ private Connection attemptConnect() throws SQLException { int attemptCount = 0; Connection sqlConnection = null; while (sqlConnection == null) { checkInternalState(); try { attemptCount++; sqlConnection = makeConnection(); if (sqlConnection.getAutoCommit() != autoCommit()) { sqlConnection.setAutoCommit(autoCommit()); } } catch (SQLException e) { if (logWarning(attemptCount)) { log.warn("Connection attempt [{}] failed for {}", attemptCount, getConnectionName(), e); } if (connectionAttempts() != -1 && attemptCount >= connectionAttempts()) { log.error("Failed to make any Jdbc Connections"); throw e; } else { log.trace(createLoggingStatement(attemptCount)); try { Thread.sleep(connectionRetryInterval()); } catch (InterruptedException e2) { throw new SQLException(e2); } continue; } } } return sqlConnection; }
From source file:org.cloudgraph.rdb.service.RDBGraphService.java
public int[] count(Query[] queries) { if (queries == null) throw new IllegalArgumentException("expected non-null 'queries' argument"); Connection con = null; try {/* w w w .j a v a2 s .co m*/ if (log.isDebugEnabled()) log.debug("getting connection"); con = ProviderManager.instance().getConnection(); if (con.getAutoCommit()) { if (log.isDebugEnabled()) log.debug("turning off connection autocommit for multi count query"); con.setAutoCommit(false); } // TODO: make transaction isolation configurable RDBMSVendorName vendor = PlasmaRuntime.getInstance() .getRDBMSProviderVendor(DataAccessProviderName.JDBC); switch (vendor) { case ORACLE: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; case MYSQL: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; default: } if (log.isDebugEnabled()) log.debug("using transaction isolation level " + con.getTransactionIsolation() + " for multi count query"); } catch (SQLException e2) { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } throw new DataAccessException(e2); } GraphQuery dispatcher = new GraphQuery(con); int[] counts = new int[queries.length]; try { for (int i = 0; i < queries.length; i++) counts[i] = dispatcher.count(queries[i]); return counts; } finally { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
From source file:org.cloudgraph.rdb.service.RDBGraphService.java
public int count(Query query) { if (query == null) throw new IllegalArgumentException("expected non-null 'query' argument"); validate(query);/*www . j a v a 2 s . c om*/ if (log.isDebugEnabled()) { log(query); } Connection con = null; try { if (log.isDebugEnabled()) log.debug("getting connection"); con = ProviderManager.instance().getConnection(); if (con.getAutoCommit()) { if (log.isDebugEnabled()) log.debug("turning off connection autocommit for count query"); con.setAutoCommit(false); } RDBMSVendorName vendor = PlasmaRuntime.getInstance() .getRDBMSProviderVendor(DataAccessProviderName.JDBC); switch (vendor) { case ORACLE: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; case MYSQL: con.setTransactionIsolation(Connection.TRANSACTION_NONE); // Oracle // does // not // support break; default: } // TODO: make transaction isolation configurable if (log.isDebugEnabled()) log.debug( "using transaction isolation level " + con.getTransactionIsolation() + " for count query"); } catch (SQLException e2) { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } throw new DataAccessException(e2); } GraphQuery dispatcher = new GraphQuery(con); try { return dispatcher.count(query); } finally { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
From source file:org.executequery.databaseobjects.impl.AbstractDatabaseObject.java
/** * Drops this named object in the database. * * @return drop statement result/* w w w. j a va 2 s . c om*/ */ public int drop() throws DataSourceException { String queryStart = null; int _type = getType(); switch (_type) { case FUNCTION: queryStart = "DROP FUNCTION "; break; case INDEX: case TABLE_INDEX: queryStart = "DROP INDEX "; break; case PROCEDURE: queryStart = "DROP PROCEDURE "; break; case SEQUENCE: queryStart = "DROP SEQUENCE "; break; case SYNONYM: queryStart = "DROP SYNONYM "; break; case SYSTEM_TABLE: case TABLE: queryStart = "DROP TABLE "; break; case TRIGGER: queryStart = "DROP TRIGGER "; break; case VIEW: queryStart = "DROP VIEW "; break; case OTHER: throw new DataSourceException("Dropping objects of this type is not currently supported"); } Statement stmnt = null; try { Connection connection = getHost().getConnection(); stmnt = connection.createStatement(); int result = stmnt.executeUpdate(queryStart + getNameWithPrefixForQuery()); if (!connection.getAutoCommit()) { connection.commit(); } return result; } catch (SQLException e) { throw new DataSourceException(e); } finally { releaseResources(stmnt); } }
From source file:org.cloudgraph.rdb.service.RDBGraphService.java
public DataGraph[] find(Query query, int maxResults) { if (query == null) throw new IllegalArgumentException("expected non-null 'query' argument"); validate(query);//from w w w .ja va2 s . co m if (log.isDebugEnabled()) { log(query); } Connection con = null; try { if (log.isDebugEnabled()) log.debug("getting connection"); con = ProviderManager.instance().getConnection(); if (con.getAutoCommit()) { if (log.isDebugEnabled()) log.debug("turning off connection autocommit for graph query"); con.setAutoCommit(false); } // TODO: make transaction isolation configurable RDBMSVendorName vendor = PlasmaRuntime.getInstance() .getRDBMSProviderVendor(DataAccessProviderName.JDBC); switch (vendor) { case ORACLE: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; case MYSQL: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; default: } if (log.isDebugEnabled()) log.debug( "using transaction isolation level " + con.getTransactionIsolation() + " for graph query"); } catch (SQLException e2) { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } throw new DataAccessException(e2); } GraphQuery dispatcher = new GraphQuery(con); try { DataGraph[] results = null; if (maxResults > 0) results = dispatcher.find(query, maxResults, new Timestamp((new Date()).getTime())); else results = dispatcher.find(query, new Timestamp((new Date()).getTime())); return results; } finally { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
From source file:org.cloudgraph.rdb.service.RDBGraphService.java
public List<DataGraph[]> find(Query[] queries) { if (queries == null) throw new IllegalArgumentException("expected non-null 'queries' argument"); Connection con = null; try {/*from www . j a v a2 s. com*/ if (log.isDebugEnabled()) log.debug("getting connection"); con = ProviderManager.instance().getConnection(); if (con.getAutoCommit()) { if (log.isDebugEnabled()) log.debug("turning off connection autocommit for multi graph query"); con.setAutoCommit(false); } // TODO: make transaction isolation configurable RDBMSVendorName vendor = PlasmaRuntime.getInstance() .getRDBMSProviderVendor(DataAccessProviderName.JDBC); switch (vendor) { case ORACLE: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; case MYSQL: con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); break; default: } if (log.isDebugEnabled()) log.debug("using transaction isolation level " + con.getTransactionIsolation() + " for multi graph query"); } catch (SQLException e2) { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } throw new DataAccessException(e2); } GraphQuery dispatcher = new GraphQuery(con); List<DataGraph[]> list = new ArrayList<DataGraph[]>(); Timestamp snapshotDate = new Timestamp((new Date()).getTime()); try { for (int i = 0; i < queries.length; i++) { validate(queries[i]); if (log.isDebugEnabled()) { log(queries[i]); } DataGraph[] results = dispatcher.find(queries[i], snapshotDate); list.add(results); } return list; } finally { if (con != null) try { if (log.isDebugEnabled()) log.debug("closing connection"); if (con != null) con.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
From source file:com.amazon.carbonado.repo.jdbc.JDBCRepository.java
/** * Gives up a connection returned from getConnection. Connection must be * yielded in same thread that retrieved it. *///from w w w .j a v a2 s. c om public void yieldConnection(Connection con) throws FetchException { try { if (con.getAutoCommit()) { closeConnection(con); } // Connections which aren't auto-commit are in a transaction. Keep // them around instead of closing them. } catch (Exception e) { throw toFetchException(e); } }