List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.cloudera.sqoop.manager.MySQLAuthTest.java
@Before public void setUp() { super.setUp(); SqoopOptions options = new SqoopOptions(AUTH_CONNECT_STRING, AUTH_TABLE_NAME); options.setUsername(AUTH_TEST_USER); options.setPassword(AUTH_TEST_PASS); LOG.debug("Setting up another MySQLAuthTest: " + AUTH_CONNECT_STRING); manager = new DirectMySQLManager(options); Connection connection = null; Statement st = null;//from w w w. j av a2s. c om try { connection = manager.getConnection(); connection.setAutoCommit(false); st = connection.createStatement(); // create the database table and populate it with data. st.executeUpdate("DROP TABLE IF EXISTS " + AUTH_TABLE_NAME); st.executeUpdate("CREATE TABLE " + AUTH_TABLE_NAME + " (" + "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + "name VARCHAR(24) NOT NULL)"); st.executeUpdate("INSERT INTO " + AUTH_TABLE_NAME + " VALUES(" + "NULL,'Aaron')"); connection.commit(); } catch (SQLException sqlE) { LOG.error("Encountered SQL Exception: " + sqlE); sqlE.printStackTrace(); fail("SQLException when running test setUp(): " + sqlE); } finally { try { if (null != st) { st.close(); } if (null != connection) { connection.close(); } } catch (SQLException sqlE) { LOG.warn("Got SQLException when closing connection: " + sqlE); } } }
From source file:com.mirth.connect.server.migration.Migrate3_5_0.java
private void migrateChannelMetadata() { PreparedStatement preparedStatement = null; ResultSet results = null;//from ww w. j ava 2s .c o m 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); DonkeyElement metadataMapElement = new DonkeyElement("<map/>"); preparedStatement = connection.prepareStatement("SELECT ID, CHANNEL FROM CHANNEL"); results = preparedStatement.executeQuery(); while (results.next()) { String channelId = ""; try { channelId = results.getString(1); String channelXml = results.getString(2); // Add metadata entry for this channel DonkeyElement metadataEntry = metadataMapElement.addChildElement("entry"); metadataEntry.addChildElement("string", channelId); DonkeyElement metadataElement = metadataEntry .addChildElement("com.mirth.connect.model.ChannelMetadata"); DonkeyElement channelElement = new DonkeyElement(channelXml); // Enabled metadataElement.addChildElement("enabled", channelElement.getChildElement("enabled").getTextContent()); // Last modified DonkeyElement lastModifiedElement = channelElement.getChildElement("lastModified"); if (lastModifiedElement != null) { try { metadataElement.addChildElementFromXml(lastModifiedElement.toXml()); } catch (DonkeyElementException e) { } } DonkeyElement propertiesElement = channelElement.getChildElement("properties"); // Pruning settings DonkeyElement pruningSettingsElement = metadataElement.addChildElement("pruningSettings"); DonkeyElement pruneMetaDataDaysElement = propertiesElement.getChildElement("pruneMetaDataDays"); DonkeyElement pruneContentDaysElement = propertiesElement.getChildElement("pruneContentDays"); DonkeyElement archiveEnabledElement = propertiesElement.getChildElement("archiveEnabled"); if (pruneMetaDataDaysElement != null) { pruningSettingsElement.addChildElement("pruneMetaDataDays", pruneMetaDataDaysElement.getTextContent()); } if (pruneContentDaysElement != null) { pruningSettingsElement.addChildElement("pruneContentDays", pruneContentDaysElement.getTextContent()); } if (archiveEnabledElement != null) { pruningSettingsElement.addChildElement("archiveEnabled", archiveEnabledElement.getTextContent()); } // Tags DonkeyElement tagsElement = propertiesElement.getChildElement("tags"); if (tagsElement != null) { try { metadataElement.addChildElementFromXml(tagsElement.toXml()); } catch (DonkeyElementException e) { } } } catch (Exception e) { logger.error("Error migrating metadata for channel " + channelId + ".", e); } } PreparedStatement updateStatement = null; try { updateStatement = connection.prepareStatement( "INSERT INTO CONFIGURATION (CATEGORY, NAME, VALUE) VALUES ('core', 'channelMetadata', ?)"); updateStatement.setString(1, metadataMapElement.toXml()); updateStatement.executeUpdate(); } finally { DbUtils.closeQuietly(updateStatement); } connection.commit(); } catch (Exception e) { logger.error("Error migrating channel metadata.", e); } finally { DbUtils.closeQuietly(results); DbUtils.closeQuietly(preparedStatement); } }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java
/** Rollback all changes made in the current transaction */ public void rollback(Connection conn) { try {//from w w w .java 2s . com conn.rollback(); conn.setAutoCommit(true); } catch (Exception e) { log.error("Failed to rollback the last transaction", e); } }
From source file:mupomat.controller.ObradaKorisnik.java
@Override public Korisnik dodajNovi(Korisnik entitet) { try {//from ww w. jav a 2s .c o m Connection veza = MySqlBazaPodataka.getConnection(); veza.setAutoCommit(false); PreparedStatement izraz = veza .prepareStatement("insert into osoba (oib,ime,prezime,email) values (?,?,?,?)"); izraz.setString(1, entitet.getOib()); izraz.setString(2, entitet.getIme()); izraz.setString(3, entitet.getPrezime()); izraz.setString(4, entitet.getEmail()); izraz.executeUpdate(); izraz = veza.prepareStatement( "insert into korisnik (oib,automat,datumregistracije,korisnickoime,lozinka,uloga,aktivan) values (?,?,now(),?,?,?,?)", Statement.RETURN_GENERATED_KEYS); izraz.setString(1, entitet.getOib()); izraz.setString(2, entitet.getAutomat()); izraz.setString(3, entitet.getKorisnickoIme()); izraz.setString(4, DigestUtils.md5Hex(entitet.getLozinka())); izraz.setString(5, entitet.getUloga()); izraz.setBoolean(6, entitet.isAktivan()); izraz.executeUpdate(); ResultSet rs = izraz.getGeneratedKeys(); rs.next(); entitet.setSifra(rs.getInt(1)); izraz.close(); veza.commit(); veza.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); return null; } return entitet; }
From source file:net.gcolin.simplerepo.search.SearchController.java
public void add(Model model, ResultType type) throws SQLException { Connection connection = null; try {//from w w w. jav a2 s . c o m connection = datasource.getConnection(); connection.setAutoCommit(false); Long versionId = new QueryRunner().query(connection, "select v.id from artifactversion v inner join artifact a on a.id = v.artifact_id " + "where a.groupId = ? and a.artifactId = ? and v.version = ?", getLong, model.getGroupId(), model.getArtifactId(), model.getVersion()); new QueryRunner().update(connection, "insert into artifacttype(version_id,packaging,classifier) VALUES (?,?,?)", versionId, type.getName(), type.getClassifier()); connection.commit(); } catch (SQLException ex) { connection.rollback(); throw ex; } finally { DbUtils.close(connection); } }
From source file:com.its.core.local.hezhou.task.ExportImageFilesReadTask.java
@Override public void execute() { long startTime = System.currentTimeMillis(); Connection conn = null; try {// www . j av a2s. c om conn = this.getConnection(); conn.setAutoCommit(false); } catch (Exception e) { log.error("" + e.getMessage(), e); return; } try { List<VehicelRecordBean> recordList = this.getExportRecordList(conn); int size = recordList.size(); log.debug("" + size + ""); if (size == 0) return; short currentExcelRow = 1; for (int i = 0; i < size; i++) { VehicelRecordBean record = (VehicelRecordBean) recordList.get(i); // this.updateRecordStatus(conn, record.getId()); String filePath = this.getImgSaveDir() + "/" + DEVICE_MAP.get(record.getDeviceIp()) + "/" + DateHelper.dateToString(record.getCatchTime(), "yyyyMMdd") + "/" + DateHelper.dateToString(record.getCatchTime(), "HH") + "/"; FileHelper.createDir(filePath); StringBuffer fileNameBuffer = new StringBuffer("X03"); fileNameBuffer.append("R").append(DEVICE_MAP.get(record.getDeviceIp())).append("D") .append(DIRECTION_MAP.get(record.getDirectionCode())).append("L") .append(record.getDrivewayNo()).append("I").append("000").append("V").append("000") .append("N").append((int) (Math.random() * (99999 - 10000)) + 10000).append("T") .append(DateHelper.dateToString(record.getCatchTime(), "yyyyMMddHHmmssSSS")); if (StringHelper.isNotEmpty(record.getPlate()) && !record.getPlate().equals("")) { fileNameBuffer.append("&").append(record.getPlate()).append("&") .append(COLOR_MAP.get(record.getPlateColorCode())); } fileNameBuffer.append("S11.JPG"); String fileName = fileNameBuffer.toString(); filePath += fileName; byte[] imageByte = ImageHelper.getImageBytes(this.getHttpPrefix() + record.getFeatureImagePath()); FileHelper.writeFile(imageByte, filePath); // log.info(""+filePath); conn.commit(); currentExcelRow++; } long currentTime = System.currentTimeMillis(); log.info("" + (currentExcelRow - 1) + " " + ((currentTime - startTime) / 1000F) + ""); } catch (Exception ex) { log.error("" + ex.getMessage(), ex); try { conn.commit(); } catch (Exception e) { } } finally { if (conn != null) { try { conn.close(); } catch (Exception ex3) { log.error(ex3); } } } }
From source file:com.aurel.track.DBScriptTest.java
/** * Run an SQL script//from w ww .j a v a 2 s. c om * @param script */ private void runSQLScript(String scriptToRunWithPath, Connection cono) { int line = 0; try { cono.setAutoCommit(false); Statement ostmt = cono.createStatement(); InputStream in = new FileInputStream(scriptToRunWithPath);//populateURL.openStream(); java.util.Scanner s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); String st = null; StringBuffer stb = new StringBuffer(); System.out.println("Running SQL script " + scriptToRunWithPath); while (s.hasNext()) { stb.append(s.nextLine().trim()); st = stb.toString(); ++line; if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*") && !st.startsWith("#")) { if (st.trim().equalsIgnoreCase("go")) { try { cono.commit(); } catch (Exception ex) { System.err.println(org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(ex)); } stb = new StringBuffer(); } else { if (st.endsWith(";")) { stb = new StringBuffer(); // clear buffer st = st.substring(0, st.length() - 1); // remove the semicolon try { if ("commit".equals(st.trim().toLowerCase()) || "go".equals(st.trim().toLowerCase())) { cono.commit(); } else { ostmt.executeUpdate(st); // LOGGER.info(st); } } catch (Exception exc) { if (!(scriptToRunWithPath.contains("Derby") && exc.getMessage().contains("DROP TABLE") && exc.getMessage().contains("not exist"))) { System.err.println("Problem executing DDL statements: " + exc.getMessage()); System.err.println("Line " + line + ": " + st); } } } else { stb.append(" "); } } } else { stb = new StringBuffer(); } } in.close(); cono.commit(); cono.setAutoCommit(true); } catch (Exception e) { System.err.println("Problem upgrading database schema in line " + line + " of file " + scriptToRunWithPath + " " + e); } }
From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java
public static Submission uploadSubmission(Project project, StudentRegistration studentRegistration, byte[] zipOutput, HttpServletRequest request, Timestamp submissionTimestamp, String clientTool, String clientVersion, String cvsTimestamp, SubmitServerDatabaseProperties db, Logger log) throws ServletException, IOException { Connection conn; try {// w w w .ja va 2s . c o m conn = db.getConnection(); } catch (SQLException e) { throw new ServletException(e); } Submission submission = null; boolean transactionSuccess = false; try { Integer baselinePK = project.getArchivePK(); int testSetupPK = project.getTestSetupPK(); byte baseLineSubmission[] = null; if (baselinePK != null && baselinePK.intValue() != 0) { baseLineSubmission = project.getBaselineZip(conn); } else if (testSetupPK != 0) { baseLineSubmission = Submission.lookupCanonicalSubmissionArchive(project.getProjectPK(), conn); } zipOutput = FixZip.adjustZipNames(baseLineSubmission, zipOutput); int archivePK = Submission.uploadSubmissionArchive(zipOutput, conn); synchronized (UPLOAD_LOCK) { final int NUMBER_OF_ATTEMPTS = 2; int attempt = 1; while (true) { try { conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); submission = Submission.submit(archivePK, studentRegistration, project, cvsTimestamp, clientTool, clientVersion, submissionTimestamp, conn); conn.commit(); transactionSuccess = true; break; } catch (SQLException e) { conn.rollback(); if (attempt++ >= NUMBER_OF_ATTEMPTS) { Submission.deleteAbortedSubmissionArchive(archivePK, conn); throw e; } } } } } catch (SQLException e) { throw new ServletException(e); } finally { rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn, db, log); } logSubmission(studentRegistration, zipOutput, submission); if (submission.getBuildStatus() == Submission.BuildStatus.NEW) WaitingBuildServer.offerSubmission(project, submission); return submission; }
From source file:com.fileanalyzer.dao.impl.FileStatisticDAOImpl.java
@Override public FileStatistic getFileStatisticById(Long id) { Connection con = null; PreparedStatement statement = null; String sql = "select * from " + FileStatistic.FileStatisticKey.TABLE + " where id=?"; FileStatistic fStat = new FileStatistic(); try {/*from w w w.j a v a 2s . c om*/ con = DBConnector.getConnection(); con.setAutoCommit(false); statement = con.prepareStatement(sql); statement.setLong(1, id); ResultSet rs = statement.executeQuery(); ResultSetToFileStatistic(rs, fStat); con.commit(); } catch (SQLException e) { handleException(e, con); } finally { doFinal(con, statement); } return fStat; }
From source file:com.iucosoft.eavertizare.dao.impl.ClientsDaoImpl.java
@Override public void saveLocal(Firma firma, List<Client> clientsList) { String query = "INSERT INTO " + firma.getTabelaClientiLocal() + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; Connection con = null; PreparedStatement ps = null;/*from ww w . j av a 2 s . c o m*/ try { con = dataSource.getConnection(); ps = con.prepareStatement(query); // Set auto-commit to false con.setAutoCommit(false); for (Client client : clientsList) { ps.setInt(1, client.getId()); ps.setString(2, client.getNume()); ps.setString(3, client.getPrenume()); ps.setInt(4, client.getNrTelefon()); ps.setString(5, client.getEmail()); ps.setTimestamp(6, (new java.sql.Timestamp(client.getDateExpirare().getTime()))); ps.setInt(7, firma.getId()); ps.setInt(8, 0); ps.addBatch(); } // Create an int[] to hold returned values int[] count = ps.executeBatch(); //Explicitly commit statements to apply changes con.commit(); } catch (SQLException e) { e.printStackTrace(); try { con.rollback(); } catch (SQLException ex) { Logger.getLogger(ClientsDaoImpl.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } }