List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.espertech.esperio.db.SupportDatabaseService.java
/** * Strictly for use in regression testing, this method provides a connection via driver manager. * @param url url//from w w w .ja v a 2 s . c om * @param username user * @param password password * @return connection */ public static Connection getConnection(String url, String username, String password) { log.info("Creating new connection instance for pool for url " + url); Driver d; try { d = (Driver) Class.forName(DRIVER).newInstance(); DriverManager.registerDriver(d); } catch (Exception e) { String message = "Failed to load and register driver class:" + e.getMessage(); log.error(message, e); throw new RuntimeException(message, e); } Connection connection; try { connection = DriverManager.getConnection(url, username, password); } catch (SQLException e) { String message = "Failed to obtain a database connection using url '" + url + "' and user '" + username + "' :" + e.getMessage(); log.error(message, e); throw new RuntimeException(message, e); } try { connection.setAutoCommit(false); } catch (SQLException e) { String message = "Failed to set auto-commit on connection '" + url + "' and user '" + username + "' :" + e.getMessage(); log.error(message, e); throw new RuntimeException(message, e); } return connection; }
From source file:fll.db.NonNumericNominees.java
/** * Add a set of nominees to the database. If the nominee already exsts, there * is no error.//from w w w . j a va 2 s.co m * * @throws SQLException */ public static void addNominees(final Connection connection, final int tournamentId, final String category, final Set<Integer> teamNumbers) throws SQLException { PreparedStatement check = null; ResultSet checkResult = null; PreparedStatement insert = null; final boolean autoCommit = connection.getAutoCommit(); try { connection.setAutoCommit(false); check = connection.prepareStatement("SELECT team_number FROM non_numeric_nominees" // + " WHERE tournament = ?" // + " AND category = ?" // + " AND team_number = ?"); check.setInt(1, tournamentId); check.setString(2, category); insert = connection.prepareStatement("INSERT INTO non_numeric_nominees" // + " (tournament, category, team_number) VALUES(?, ?, ?)"); insert.setInt(1, tournamentId); insert.setString(2, category); for (final int teamNumber : teamNumbers) { check.setInt(3, teamNumber); insert.setInt(3, teamNumber); checkResult = check.executeQuery(); if (!checkResult.next()) { insert.executeUpdate(); } } connection.commit(); } finally { connection.setAutoCommit(autoCommit); SQLFunctions.close(checkResult); SQLFunctions.close(check); SQLFunctions.close(insert); } }
From source file:com.weibo.datasys.common.db.DBManager.java
/** * ???????//from w w w . jav a 2 s . c om * * @return * @throws DBException * ????? */ public static Connection getConnection(String dsname) throws DBException { Connection connection = null; BasicDataSource ds = dsMap.get(dsname); if (ds == null) { throw new DBException("NO DataSource for dsname: " + dsname); } try { connection = ds.getConnection(); connection.setAutoCommit(true); } catch (Exception e) { logger.error("[GetConnError] - e.msg={} | ds={}.", e.getMessage(), dsname); throw new DBException(e); } return connection; }
From source file:dk.netarkivet.archive.arcrepositoryadmin.ArchiveDBConnection.java
/** * Get a connection to the harvest definition database from the pool. * The pool is configured via the following configuration properties: * <ul>/* w ww. j a va 2s . com*/ * <li>@see {@link ArchiveSettings#DB_POOL_MIN_SIZE}</li> * <li>@see {@link ArchiveSettings#DB_POOL_MAX_SIZE}</li> * <li>@see {@link ArchiveSettings#DB_POOL_ACQ_INC}</li> * </ul> * Note that the connection obtained must be returned to the pool by calling * {@link #release(Connection)}. * @return a connection to the harvest definition database * @throws IOFailure if we cannot connect to the database (or find the * driver). */ public static synchronized Connection get() { DBSpecifics dbSpec = DBSpecifics.getInstance(); String jdbcUrl = getArchiveUrl(); int tries = 0; Connection con = null; while (tries < maxdatabaseRetries && con == null) { tries++; try { if (dataSource == null) { initDataSource(dbSpec, jdbcUrl); } con = dataSource.getConnection(); con.setAutoCommit(false); // different from in // HarvestDBConnection } catch (SQLException e) { final String message = "Can't connect to database with DBurl: '" + jdbcUrl + "' using driver '" + dbSpec.getDriverClassName() + "'" + "\n" + ExceptionUtils.getSQLExceptionCause(e); if (log.isWarnEnabled()) { log.warn(message, e); } if (tries < maxdatabaseRetries) { log.info("Will wait " + delaybetweenretries / TimeUtils.SECOND_IN_MILLIS + " before retrying"); try { Thread.sleep(delaybetweenretries); } catch (InterruptedException e1) { // ignore this exception log.trace("Interruption ignored.", e1); } } else { throw new IOFailure(message, e); } } } return con; }
From source file:com.concursive.connect.web.modules.profile.utils.ProjectCopier.java
public static Requirement cloneRequirement(CloneBean bean, Connection db, int groupId, int userId, int requirementId) throws SQLException { Requirement requirement = null;//from w w w. ja v a 2 s . c o m try { db.setAutoCommit(false); // Load permissions and resources for this member LOG.debug("ProjectCopier-> RequirementId: " + requirementId); Project project = new Project(db, bean.getProjectId()); TeamMember member = new TeamMember(db, project.getId(), userId); User user = UserUtils.loadUser(userId); LookupList roleList = new LookupList(db, "lookup_project_role"); // Load old requirement, change some values, save as new requirement requirement = new Requirement(db, requirementId); // Outlines, Activities, Activity Folders (no notes yet) if (hasPermission(db, project, user, member, "project-plan-view", roleList)) { requirement.setEnteredBy(userId); requirement.setModifiedBy(userId); requirement.setEntered((Timestamp) null); requirement.setModified((Timestamp) null); requirement.setShortDescription(requirement.getShortDescription() + " (copy)"); boolean resetStatus = false; long offset = 0; if (bean.getResetActivityStatus()) { resetStatus = true; } requirement.clone(db, project.getId(), offset, resetStatus); } db.commit(); } catch (Exception e) { LOG.error("ProjectCopier-> cloneRequirement", e); db.rollback(); } finally { db.setAutoCommit(true); } return requirement; }
From source file:gridool.db.helpers.GridDbUtils.java
@Nonnull public static Connection getPrimaryDbConnection(final DBAccessor dba, boolean autoCommit) throws GridException { final Connection conn; try {//from w ww .ja va 2 s.co m conn = dba.getPrimaryDbConnection(); if (conn.getAutoCommit() != autoCommit) { conn.setAutoCommit(autoCommit); } } catch (SQLException e) { LOG.error(e); throw new GridException("failed connecting to the primary database: " + dba.getPrimaryDbName()); } return conn; }
From source file:com.aurel.track.dbase.UpdateDbSchema.java
/** * Run an SQL script/*from w ww . ja va 2 s . c o m*/ * @param script */ @SuppressWarnings("resource") private static void runSQLScript(String script, int maxValue, String progressText) { String folderName = getDbScriptFolder(); int line = 0; int noOfLines = 0; int progress = 0; Connection cono = null; try { long start = new Date().getTime(); cono = InitDatabase.getConnection(); cono.setAutoCommit(false); Statement ostmt = cono.createStatement(); script = "/dbase/" + folderName + "/" + script; URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(script); InputStream in = populateURL.openStream(); java.util.Scanner s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); while (s.hasNext()) { ++noOfLines; s.nextLine(); } int mod = noOfLines / maxValue; in.close(); in = populateURL.openStream(); s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); String st = null; StringBuilder stb = new StringBuilder(); int modc = 0; progress = Math.round(new Float(mod) / new Float(noOfLines) * maxValue); LOGGER.info("Running SQL script " + script); while (s.hasNext()) { stb.append(s.nextLine().trim()); st = stb.toString(); ++line; ++modc; if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*") && !st.startsWith("#")) { if (st.trim().equalsIgnoreCase("go")) { try { cono.commit(); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } stb = new StringBuilder(); } else { if (st.endsWith(";")) { stb = new StringBuilder(); // 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); if (mod > 4 && modc >= mod) { modc = 0; ApplicationStarter.getInstance().actualizePercentComplete(progress, progressText); } } } catch (Exception exc) { if (!("Derby".equals(folderName) && exc.getMessage().contains("DROP TABLE") && exc.getMessage().contains("not exist"))) { LOGGER.error("Problem executing DDL statements: " + exc.getMessage()); LOGGER.error("Line " + line + ": " + st); } } } else { stb.append(" "); } } } else { stb = new StringBuilder(); } } in.close(); cono.commit(); cono.setAutoCommit(true); long now = new Date().getTime(); LOGGER.info("Database schema creation took " + (now - start) / 1000 + " seconds."); } catch (Exception e) { LOGGER.error("Problem upgrading database schema in line " + line + " of file " + script, e); } finally { try { if (cono != null) { cono.close(); } } catch (Exception e) { LOGGER.info("Closing the connection failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } }
From source file:com.mirth.connect.server.util.DatabaseUtil.java
public static void executeScript(List<String> script, boolean ignoreErrors) throws Exception { SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager(); Connection conn = null; ResultSet resultSet = null;/*from w w w . j a va 2 s .com*/ Statement statement = null; try { sqlSessionManger.startManagedSession(); conn = sqlSessionManger.getConnection(); /* * Set auto commit to false or an exception will be thrown when trying to rollback */ conn.setAutoCommit(false); statement = conn.createStatement(); for (String statementString : script) { statementString = statementString.trim(); if (statementString.length() > 0) { try { statement.execute(statementString); conn.commit(); } catch (SQLException se) { if (!ignoreErrors) { throw se; } else { logger.error("Error was encountered and ignored while executing statement: " + statementString, se); conn.rollback(); } } } } } catch (Exception e) { throw new Exception(e); } finally { DbUtils.closeQuietly(statement); DbUtils.closeQuietly(resultSet); DbUtils.closeQuietly(conn); sqlSessionManger.close(); } }
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); }/*from ww w . j a 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:de.maklerpoint.office.LocalDatabase.DdlUtilsHelper.java
/** * /* w w w.j a va 2s. c om*/ * @param dataSource * @param targetModel * @param alterDb */ public static void copyDatabase(Connection con, DataSource dataSource, Database targetModel, boolean alterDb) throws SQLException { Platform platform = PlatformFactory.createNewPlatformInstance("derby"); platform.createDatabase("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:maklerpointDB", null, null, null); if (alterDb) { platform.alterTables(targetModel, false); } else { platform.createTables(con, targetModel, true, true); con.setAutoCommit(true); } }