List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java
/** * ?/*from ww w. j a va 2 s. c om*/ * @param list sql? */ public void executeBatch(final List<String> list) { Connection conn = null; Statement st = null; try { conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); conn.setAutoCommit(false); // ?? st = conn.createStatement(); for (int i = 1, j = list.size(); i < j; i++) { String sql = list.get(i); st.addBatch(sql); if (i % 240 == 0) {//?240?sql??? st.executeBatch(); conn.commit(); st.clearBatch(); } else if (i % j == 0) {//?? st.executeBatch(); conn.commit(); st.clearBatch(); } } } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { closeAll(st, conn); } }
From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java
@Test public void testCommitRollback() throws Exception { Connection conn = new MyProxy(); try {/* www.j av a 2 s .c om*/ try { conn.setAutoCommit(conn.getAutoCommit()); } catch (SQLException e) { } try { conn.setAutoCommit(false); conn.commit(); } catch (SQLException e) { } try { conn.setAutoCommit(false); conn.rollback(); } catch (SQLException e) { } try { conn.setAutoCommit(false); conn.rollback(conn.setSavepoint()); } catch (SQLException e) { } try { conn.setAutoCommit(false); conn.rollback(conn.setSavepoint("test")); } catch (SQLException e) { } try { conn.setAutoCommit(false); conn.releaseSavepoint(conn.setSavepoint("test2")); } catch (SQLException e) { } } finally { JdbcUtil.closeQuietly(conn); } }
From source file:com.ilopez.jasperemail.JasperEmail.java
private JasperPrint generateReport(String reportDefinitionFile, String jdbcClass, String jdbcURL, String databaseUsername, String databasePassword, String dbHost, Map parameters) throws FileNotFoundException, JRException, SQLException, ClassNotFoundException, Exception { // Get the file Extension of the RDF String ext = FilenameUtils.getExtension(reportDefinitionFile).toUpperCase(); JasperReport report;//from w w w . ja v a2 s. c o m if (ext.contains("JASPER")) { // If it is a JASPER file, then we do not need to compile it, so load it in. report = (JasperReport) JRLoader.loadObject((new File(reportDefinitionFile))); } else if (ext.contains("JRXML")) { // If it is a JRXML file we will need to compile the report Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, null, "Reading Input File " + reportDefinitionFile); InputStream input = new FileInputStream(new File(reportDefinitionFile)); JasperDesign design = JRXmlLoader.load(input); report = JasperCompileManager.compileReport(design); Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, null, "Compiled Report From File " + reportDefinitionFile); } else { throw new Exception("Unknown Jasper Report Extensions - JRXML or JASPER allowed only."); } // Connect to the Database with the supplied jdbcClass and jdbcURL, and Username/Password. Class.forName(jdbcClass); String connectionStatement = jdbcURL; Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, "Connecting to Database " + jdbcURL); Properties connectionProperties = new Properties(); if (databaseUsername != null) { connectionProperties.setProperty("user", databaseUsername); } if (databasePassword != null) { connectionProperties.setProperty("password", databasePassword); } Connection conn = DriverManager.getConnection(connectionStatement, connectionProperties); Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, "Database Connected " + jdbcURL); conn.setAutoCommit(false); // run report and write output JasperPrint print = JasperFillManager.fillReport(report, parameters, conn); Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, "Jasper Print Prepared"); conn.close(); return print; }
From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.common.JdbcTransactionListener.java
private Connection getConnection() { Connection connection = (Connection) AlfrescoTransactionSupport.getResource(SYNCHRO_CONTEXT_KEY); if (connection == null) { if (logger.isDebugEnabled()) logger.debug("Creating new connection for transaction with id " + AlfrescoTransactionSupport.getTransactionId()); connection = DataSourceUtils.getConnection(dataSource); try {/*from ww w . j av a2s . c om*/ connection.setAutoCommit(false); } catch (SQLException e) { logger.error("Cannot set autocommit mode on the connection"); logger.debug(e); } AlfrescoTransactionSupport.bindResource(SYNCHRO_CONTEXT_KEY, connection); AlfrescoTransactionSupport.bindListener(this); if (logger.isDebugEnabled()) logger.debug("Attached connection to transaction " + AlfrescoTransactionSupport.getTransactionId()); } return connection; }
From source file:fitmon.WorkoutData.java
public double calBurned(String date, int userId) throws SQLException { PreparedStatement st = null;/*from w w w . j a v a2 s. com*/ Connection conn = null; double calBurned = 0; try { String query = "select date,sum(calories) from Workout where userId=" + userId + " and date='" + date + "'"; Class.forName("com.mysql.jdbc.Driver"); conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/fitmon", "root", "april-23"); st = conn.prepareStatement(query); conn.setAutoCommit(false); ResultSet rs = st.executeQuery(query); while (rs.next()) { calBurned = rs.getDouble("sum(calories)"); } st.close(); conn.close(); } catch (ClassNotFoundException ce) { ce.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { if (st != null) { st.close(); } if (conn != null) { conn.close(); } } return calBurned; }
From source file:com.flexive.core.storage.GenericDBStorage.java
/** * {@inheritDoc}// w w w.ja va 2 s.c om */ @Override public void importDivision(Connection _con, ZipFile zip) throws Exception { long startTime = System.currentTimeMillis(); GenericDivisionImporter importer = getDivisionImporter(); FxDivisionExportInfo exportInfo = importer.getDivisionExportInfo(zip); if (FxSharedUtils.getDBVersion() != exportInfo.getSchemaVersion()) { LOG.warn("DB Version mismatch! Current:" + FxSharedUtils.getDBVersion() + ", exported schema:" + exportInfo.getSchemaVersion()); } boolean isNonTX = importer.importRequiresNonTXConnection(); Connection con = isNonTX ? Database.getNonTXDataSource().getConnection() : _con; boolean autoCommit = false; if (isNonTX) { autoCommit = con.getAutoCommit(); con.setAutoCommit(false); con.commit(); //ensure a "clean" connection } Exception inner = null; try { importer.wipeDivisionData(con); if (isNonTX) con.commit(); Statement stmt = con.createStatement(); if (isNonTX) con.commit(); try { importer.importLanguages(con, zip); if (isNonTX) con.commit(); importer.importMandators(con, zip); if (isNonTX) con.commit(); importer.importSecurity(con, zip); if (isNonTX) con.commit(); importer.importWorkflows(con, zip); if (isNonTX) con.commit(); importer.importConfigurations(con, zip); if (isNonTX) con.commit(); importer.importBinaries(con, zip); if (isNonTX) con.commit(); stmt.execute(getReferentialIntegrityChecksStatement(false)); importer.importStructures(con, zip); if (isNonTX) con.commit(); importer.importHierarchicalContents(con, zip); if (isNonTX) con.commit(); importer.importScripts(con, zip); if (isNonTX) con.commit(); importer.importTree(con, zip); if (isNonTX) con.commit(); importer.importHistory(con, zip); if (isNonTX) con.commit(); importer.importResources(con, zip); if (isNonTX) con.commit(); importer.importBriefcases(con, zip); if (isNonTX) con.commit(); importer.importFlatStorages(con, zip, exportInfo); if (isNonTX) con.commit(); importer.importSequencers(con, zip); if (isNonTX) con.commit(); } catch (Exception e) { if (isNonTX) con.rollback(); inner = e; throw e; } finally { if (isNonTX) con.commit(); stmt.execute(getReferentialIntegrityChecksStatement(true)); } if (isNonTX) con.commit(); //rebuild fulltext index FulltextIndexer ft = StorageManager.getStorageImpl().getContentStorage(TypeStorageMode.Hierarchical) .getFulltextIndexer(null, con); ft.rebuildIndex(); if (isNonTX) con.commit(); } catch (Exception e) { if (isNonTX) con.rollback(); if (inner != null) { LOG.error(e); throw inner; } throw e; } finally { if (isNonTX) { con.commit(); con.setAutoCommit(autoCommit); Database.closeObjects(GenericDBStorage.class, con, null); } LOG.info(" Importing took " + FxFormatUtils.formatTimeSpan((System.currentTimeMillis() - startTime))); } }
From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java
/** * ?//from w w w .java 2 s .co m * @param list sql? */ public void executeBatchByPrepare(String sql, final List<String> list) { Connection conn = null; PreparedStatement st = null; try { conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection(); conn.setAutoCommit(false); // ?? st = conn.prepareStatement(sql); for (int i = 1, j = list.size(); i < j; i++) { Object objs = list.get(i - 1); if (objs instanceof List) { List<Object> values = (List<Object>) objs; for (int h = 1, k = values.size(); h <= k; k++) { Object value = values.get(k - 1); setParameters(st, k, value); } } else { setParameters(st, i, objs); } st.addBatch(sql); if (i % 240 == 0) {//?240?sql??? st.executeBatch(); conn.commit(); st.clearBatch(); } else if (i % j == 0) {//?? st.executeBatch(); conn.commit(); st.clearBatch(); } } } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { closeAll(st, conn); } }
From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java
/** * Opens a SQL client editor on the specified connection using the provided sql script. This * internal method returns the newly initialized connection that this editor uses so that * callers can run queries with it./*from w ww . j a v a2 s. c om*/ * * @param conn the descriptor of the connection on which the client should be initialized * @param queryScript the {@link ISQLScript} that the client editor will use * @return the editor input */ private SQLClientEditorInput openSqlClientEditor(IConnection conn, ISQLScript queryScript) { // Initializing editor input final SQLClientEditorInput input = new SQLClientEditorInput(queryScript, conn); // Initializing connection try { Connection sqlConnection = connectionService.connect(conn); sqlConnection.setAutoCommit(AUTOCOMMIT_DEFAULT); input.setSqlConnection(sqlConnection); } catch (SQLException e) { throw new ErrorException("Could not establish connection : " + e.getMessage(), e); } // Initializing result view final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { page.openEditor(input, SQLFullClientEditor.EDITOR_ID); final IViewPart part = getSQLResultViewFor(input, false); final IViewSite site = part.getViewSite(); page.showView(site.getId(), site.getSecondaryId(), IWorkbenchPage.VIEW_VISIBLE); } catch (PartInitException e) { throw new ErrorException("Unable to open SQL client: " + e.getMessage(), e); } return input; }
From source file:com.mirth.connect.server.migration.Migrate3_3_0.java
private void migrateCodeTemplates() { PreparedStatement preparedStatement = null; ResultSet results = null;//from www .j a v a2 s . com try { Connection connection = getConnection(); /* * MIRTH-1667: Derby fails if autoCommit is set to true and there are a large number of * results. The following error occurs: "ERROR 40XD0: Container has been closed" */ connection.setAutoCommit(false); List<String> codeTemplateIds = new ArrayList<String>(); preparedStatement = connection.prepareStatement("SELECT ID, CODE_TEMPLATE FROM OLD_CODE_TEMPLATE"); results = preparedStatement.executeQuery(); PreparedStatement updateStatement = null; updateStatement = connection.prepareStatement( "INSERT INTO CODE_TEMPLATE (ID, NAME, REVISION, CODE_TEMPLATE) VALUES (?, ?, ?, ?)"); try { while (results.next()) { String codeTemplateId = ""; try { codeTemplateId = results.getString(1); String codeTemplate = results.getString(2); String name = new DonkeyElement(codeTemplate).getChildElement("name").getTextContent(); Integer revision = 1; updateStatement.setString(1, codeTemplateId); updateStatement.setString(2, name); updateStatement.setInt(3, revision); updateStatement.setString(4, codeTemplate); updateStatement.executeUpdate(); codeTemplateIds.add(codeTemplateId); } catch (Exception e) { logger.error("Error migrating code template " + codeTemplateId + ".", e); } } } finally { DbUtils.closeQuietly(updateStatement); } try { String libraryId = UUID.randomUUID().toString(); String name = "Library 1"; Integer revision = 1; DonkeyElement libraryElement = new DonkeyElement("<codeTemplateLibrary/>"); libraryElement.setAttribute("version", "3.3.0"); libraryElement.addChildElement("id", libraryId); libraryElement.addChildElement("name", name); libraryElement.addChildElement("revision", String.valueOf(revision)); try { libraryElement.addChildElementFromXml(serializer.serialize(Calendar.getInstance())) .setNodeName("lastModified"); } catch (DonkeyElementException e) { throw new SerializerException("Failed to migrate code template library last modified date.", e); } libraryElement.addChildElement("description", "This library was added upon migration to version 3.3.0. It includes all pre-existing\ncode templates, and is set to be included on all pre-existing and new channels.\n\nYou should create your own new libraries and assign code templates to them as you\nsee fit. You should also link libraries to specific channels, so that you're not\nnecessarily including all code templates on all channels all the time."); libraryElement.addChildElement("includeNewChannels", "true"); libraryElement.addChildElement("enabledChannelIds"); libraryElement.addChildElement("disabledChannelIds"); DonkeyElement codeTemplatesElement = libraryElement.addChildElement("codeTemplates"); for (String codeTemplateId : codeTemplateIds) { DonkeyElement codeTemplateElement = codeTemplatesElement.addChildElement("codeTemplate"); codeTemplateElement.setAttribute("version", "3.3.0"); codeTemplateElement.addChildElement("id", codeTemplateId); } String libraryXml = libraryElement.toXml(); try { updateStatement = connection.prepareStatement( "INSERT INTO CODE_TEMPLATE_LIBRARY (ID, NAME, REVISION, LIBRARY) VALUES (?, ?, ?, ?)"); updateStatement.setString(1, libraryId); updateStatement.setString(2, name); updateStatement.setInt(3, revision); updateStatement.setString(4, libraryXml); updateStatement.executeUpdate(); } finally { DbUtils.closeQuietly(updateStatement); } } catch (Exception e) { logger.error("Error creating code template library for migration.", e); } connection.commit(); } catch (SQLException e) { logger.error("Error migrating code templates.", e); } finally { DbUtils.closeQuietly(results); DbUtils.closeQuietly(preparedStatement); } }
From source file:eionet.cr.dao.virtuoso.VirtuosoHarvestScriptDAO.java
/** * @see eionet.cr.dao.HarvestScriptDAO#insert(eionet.cr.dto.HarvestScriptDTO.TargetType, java.lang.String, java.lang.String, * java.lang.String, boolean, boolean, Phase) *///from w ww . j a v a 2 s .co m @Override public int insert(TargetType targetType, String targetUrl, String title, String script, boolean active, boolean runOnce, Phase phase) throws DAOException { String sourceUrl = targetType != null && targetType.equals(TargetType.SOURCE) ? targetUrl : null; String typeUrl = targetType != null && targetType.equals(TargetType.TYPE) ? targetUrl : null; if (phase == null) { phase = HarvestScriptDTO.DEFAULT_PHASE; } Connection conn = null; try { conn = getSQLConnection(); conn.setAutoCommit(false); ArrayList<Object> values = new ArrayList<Object>(); values.add(sourceUrl == null ? "" : sourceUrl); values.add(typeUrl == null ? "" : typeUrl); Object o = SQLUtil.executeSingleReturnValueQuery(GET_LAST_POSITION_SQL, values, conn); int position = o == null ? 1 : Integer.parseInt(o.toString()) + 1; values = new ArrayList<Object>(); values.add(sourceUrl); values.add(typeUrl); values.add(title); values.add(script); values.add(Integer.valueOf(position)); values.add(YesNoBoolean.format(active)); values.add(YesNoBoolean.format(runOnce)); values.add(phase.name()); int result = SQLUtil.executeUpdateReturnAutoID(INSERT_SQL, values, conn); conn.commit(); return result; } catch (Exception e) { SQLUtil.rollback(conn); throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(conn); } }