List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.mirth.connect.server.migration.Migrate3_0_0.java
private void migrateCodeTemplateTable() { Logger logger = Logger.getLogger(getClass()); PreparedStatement preparedStatement = null; ResultSet results = null;/*from ww w . ja v a 2 s . c o m*/ try { /* * 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 connection = getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement( "SELECT ID, NAME, CODE_SCOPE, CODE_TYPE, TOOLTIP, CODE FROM OLD_CODE_TEMPLATE"); results = preparedStatement.executeQuery(); while (results.next()) { String id = ""; try { id = results.getString(1); String name = results.getString(2); String codeScope = results.getString(3); String codeType = results.getString(4); String toolTip = results.getString(5); String code = results.getString(6); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("codeTemplate"); document.appendChild(element); DonkeyElement codeTemplate = new DonkeyElement(element); codeTemplate.addChildElement("id", id); codeTemplate.addChildElement("name", name); codeTemplate.addChildElement("tooltip", toolTip); codeTemplate.addChildElement("code", code); codeTemplate.addChildElement("type", codeType); codeTemplate.addChildElement("scope", codeScope); // If the starting schema version is 2.0 or later, we need to add the version node to the XML. if (getStartingVersion() != null && getStartingVersion().ordinal() >= Version.V7.ordinal()) { codeTemplate.addChildElement("version", "2.0"); } String serializedCodeTemplate = new DonkeyElement(element).toXml(); PreparedStatement updateStatement = null; try { updateStatement = connection .prepareStatement("INSERT INTO CODE_TEMPLATE (ID, CODE_TEMPLATE) VALUES (?, ?)"); updateStatement.setString(1, id); updateStatement.setString(2, serializedCodeTemplate); updateStatement.executeUpdate(); updateStatement.close(); } finally { DbUtils.closeQuietly(updateStatement); } } catch (Exception e) { logger.error("Error migrating code template " + id + ".", e); } } connection.commit(); } catch (Exception e) { logger.error("Error migrating code templates.", e); } finally { DbUtils.closeQuietly(results); DbUtils.closeQuietly(preparedStatement); } }
From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java
@Test public void testBatchInsert() throws Exception { Connection conn = methodWatcher.getOrCreateConnection(); //insert a single record conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into batch_test (col1,col2,col3) values (?,?,?)"); int iterCount = 10; for (int i = 0; i < iterCount; i++) { ps.setInt(1, i);/*from w w w .java 2s. c o m*/ ps.setInt(2, i); ps.setInt(3, i); ps.addBatch(); } int[] results = ps.executeBatch(); Assert.assertEquals("results returned correct", 10, results.length); ps.close(); ps = conn.prepareStatement("select count(*) from batch_test"); ResultSet rs = ps.executeQuery(); rs.next(); Assert.assertEquals("results returned correct", 10, rs.getInt(1)); }
From source file:com.tera.common.database.query.CQueryService.java
@Override public <T> boolean batchUpdate(String batchUpdate, BatchUpdateQuery<T> query, String errorMessage, boolean autoCommit) { Connection connection = null; PreparedStatement statement = null; try {/*from www.j a va 2 s . c om*/ connection = databaseFactory.getConnection(); statement = connection.prepareStatement(batchUpdate); connection.setAutoCommit(autoCommit); Collection<T> items = query.getItems(); for (T item : items) { query.handleBatch(statement, item); statement.addBatch(); } statement.executeBatch(); if (!autoCommit) { connection.commit(); } } catch (Exception e) { if (errorMessage == null) log.error("Failed to execute BatchUpdate query {}", e, e); else log.error(errorMessage + " " + e, e); return false; } finally { close(null, statement, connection); } return true; }
From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java
public int deleteExchangesByIds(String[] ids) throws AuditorException { Connection connection = null; boolean restoreAutoCommit = false; try {/*from ww w . ja v a 2s. c o m*/ connection = dataSource.getConnection(); if (connection.getAutoCommit()) { connection.setAutoCommit(false); restoreAutoCommit = true; } for (int row = 0; row < ids.length; row++) { adapter.doRemoveData(connection, ids[row]); } connection.commit(); return ids.length; } catch (Exception e) { throw new AuditorException("Could not delete exchanges", e); } finally { close(connection, restoreAutoCommit); } }
From source file:com.cloudera.sqoop.manager.DirectMySQLTest.java
@Before public void setUp() { super.setUp(); SqoopOptions options = new SqoopOptions(MySQLTestUtils.CONNECT_STRING, getTableName()); options.setUsername(MySQLTestUtils.getCurrentUser()); LOG.debug("Setting up another DirectMySQLTest: " + MySQLTestUtils.CONNECT_STRING); manager = new DirectMySQLManager(options); Connection connection = null; Statement st = null;/*ww w . j a v a 2 s . co m*/ 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 " + getTableName()); st.executeUpdate("CREATE TABLE " + getTableName() + " (" + "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " + "name VARCHAR(24) NOT NULL, " + "start_date DATE, " + "salary FLOAT, " + "dept VARCHAR(32))"); st.executeUpdate("INSERT INTO " + getTableName() + " VALUES(" + "NULL,'Aaron','2009-05-14',1000000.00,'engineering')"); st.executeUpdate( "INSERT INTO " + getTableName() + " VALUES(" + "NULL,'Bob','2009-04-20',400.00,'sales')"); st.executeUpdate( "INSERT INTO " + getTableName() + " VALUES(" + "NULL,'Fred','2009-01-23',15.00,'marketing')"); 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.splicemachine.mrio.api.core.SMSQLUtil.java
public void disableAutoCommit(Connection conn) throws SQLException { conn.setAutoCommit(false); }
From source file:com.splout.db.engine.MySQLOutputFormat.java
public void initPartition(int partition, Path local) throws IOException { Path mysqlDb = new Path(local.getParent(), partition + ""); LOG.info("Initializing SQL connection [" + partition + "]"); try {//from ww w . j av a 2 s .c o m PortLock portLock = PortUtils.getNextAvailablePort(EmbeddedMySQLConfig.DEFAULT_PORT); EmbeddedMySQL mySQL = null; EmbeddedMySQLConfig config = null; HashMap<String, Object> customConfig = new HashMap<String, Object>(); // Fixing memory for indexation. Main important parameters is myisam_sort_buffer_size // and key_buffer_size. See http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html long totalMem = getConf().getLong(GLOBAL_MEMORY_AVAILABLE_FOR_INDEXING, 100 * 1024 * 1024); double shareForSortBuffer = 0.9; customConfig.put("myisam_sort_buffer_size", (long) (shareForSortBuffer * totalMem)); customConfig.put("key_buffer_size", (long) ((1 - shareForSortBuffer) * totalMem)); customConfig.put("myisam_max_sort_file_size", 9223372036854775807l); try { File mysqlDir = new File(mysqlDb.toString()); LOG.info("Going to instantiate a MySQLD in: " + mysqlDir + ", port [" + portLock.getPort() + "] (partition: " + partition + ")"); config = new EmbeddedMySQLConfig(portLock.getPort(), EmbeddedMySQLConfig.DEFAULT_USER, EmbeddedMySQLConfig.DEFAULT_PASS, mysqlDir, customConfig); mySQL = new EmbeddedMySQL(config); mySQL.start(true); } catch (Exception e) { throw e; } finally { portLock.release(); } mySQLs.put(partition, mySQL); // MySQL is successfully started at this point, or an Exception would have been thrown. Class.forName(EmbeddedMySQL.DRIVER); Connection conn = DriverManager.getConnection(config.getLocalJDBCConnection(GENERATED_DB_NAME), config.getUser(), config.getPass()); conn.setAutoCommit(false); connCache.put(partition, conn); Statement st = conn.createStatement(); // Init transaction for (String sql : getPreSQL()) { LOG.info("Executing: " + sql); st.execute(sql); } st.execute("BEGIN"); st.close(); Map<String, PreparedStatement> stMap = new HashMap<String, PreparedStatement>(); stCache.put(partition, stMap); } catch (Exception e) { throw new IOException(e); } }
From source file:org.cfr.capsicum.datasource.CayenneTransactionManager.java
@Override protected void doCleanupAfterCompletion(Object transaction) { CayenneTransactionObject txObject = (CayenneTransactionObject) transaction; // Remove the connection holder from the thread, if exposed. if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.unbindResource(this.dataSource); }// w w w . j a va2 s.co m // Reset connection. Connection con = txObject.getConnectionHolder().getConnection(); try { if (txObject.isMustRestoreAutoCommit()) { con.setAutoCommit(true); } DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel()); } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } if (txObject.isNewConnectionHolder()) { if (logger.isDebugEnabled()) { logger.debug("Releasing JDBC Connection [" + con + "] after transaction"); } DataSourceUtils.releaseConnection(con, this.dataSource); } txObject.getConnectionHolder().clear(); }
From source file:com.mirth.connect.server.migration.Migrate3_0_0.java
private void migrateChannelTable() { PreparedStatement preparedStatement = null; ResultSet results = null;/*from w w w.j a va 2 s. c o m*/ try { /* * 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 connection = getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement( "SELECT ID, NAME, DESCRIPTION, IS_ENABLED, VERSION, REVISION, LAST_MODIFIED, SOURCE_CONNECTOR, DESTINATION_CONNECTORS, PROPERTIES, PREPROCESSING_SCRIPT, POSTPROCESSING_SCRIPT, DEPLOY_SCRIPT, SHUTDOWN_SCRIPT FROM OLD_CHANNEL"); results = preparedStatement.executeQuery(); while (results.next()) { String channelId = ""; try { channelId = results.getString(1); String name = results.getString(2); String description = results.getString(3); Boolean isEnabled = results.getBoolean(4); String version = results.getString(5); Integer revision = results.getInt(6); Calendar lastModified = Calendar.getInstance(); lastModified.setTimeInMillis(results.getTimestamp(7).getTime()); String sourceConnector = results.getString(8); String destinationConnectors = results.getString(9); String properties = results.getString(10); String preprocessingScript = results.getString(11); String postprocessingScript = results.getString(12); String deployScript = results.getString(13); String shutdownScript = results.getString(14); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("channel"); document.appendChild(element); DonkeyElement channel = new DonkeyElement(element); channel.addChildElement("id", channelId); channel.addChildElement("name", name); channel.addChildElement("description", description); channel.addChildElement("enabled", Boolean.toString(isEnabled)); channel.addChildElement("version", version); DonkeyElement lastModifiedElement = channel.addChildElement("lastModified"); lastModifiedElement.addChildElement("time", String.valueOf(lastModified.getTimeInMillis())); lastModifiedElement.addChildElement("timezone", lastModified.getTimeZone().getDisplayName()); channel.addChildElement("revision", String.valueOf(revision)); channel.addChildElementFromXml(sourceConnector).setNodeName("sourceConnector"); channel.addChildElementFromXml(destinationConnectors).setNodeName("destinationConnectors"); channel.addChildElementFromXml(properties); channel.addChildElement("preprocessingScript", preprocessingScript); channel.addChildElement("postprocessingScript", postprocessingScript); channel.addChildElement("deployScript", deployScript); channel.addChildElement("shutdownScript", shutdownScript); String serializedChannel = channel.toXml(); PreparedStatement updateStatement = null; try { updateStatement = connection.prepareStatement( "INSERT INTO CHANNEL (ID, NAME, REVISION, CHANNEL) VALUES (?, ?, ?, ?)"); updateStatement.setString(1, channelId); updateStatement.setString(2, name); updateStatement.setInt(3, revision); updateStatement.setString(4, serializedChannel); updateStatement.executeUpdate(); updateStatement.close(); } finally { DbUtils.closeQuietly(updateStatement); } } catch (Exception e) { logger.error("Error migrating channel " + channelId + ".", e); } } connection.commit(); } catch (SQLException e) { logger.error("Error migrating channels.", e); } finally { DbUtils.closeQuietly(results); DbUtils.closeQuietly(preparedStatement); } }
From source file:com.globalsight.everest.permission.Permission.java
/** * Adds the given permission to the database PERMISSION table if it does not * already exist in the map. This does update one by one, but this method * should almost never be called except on startup and if new permissions * were actually added, so there is no reason to batch. * /*from ww w .j a v a2 s .co m*/ * @param p_added * set to true if anything was added * @param p_perm * permission name (should be above defined constant) */ static private boolean addPermission(long id, String p_perm) { boolean added = false; Connection c = null; PreparedStatement stmt = null; try { c = ConnectionPool.getConnection(); c.setAutoCommit(false); if (s_idMap.isEmpty()) { stmt = c.prepareStatement(SQL_INSERT_FIRST_PERM); stmt.executeUpdate(); s_idMap.put(p_perm, new Long(1)); if (logger.isDebugEnabled()) { logger.debug("Added " + p_perm + " to the table."); } } else if (!s_idMap.containsKey(p_perm)) { stmt = c.prepareStatement(SQL_INSERT_PERM); stmt.setLong(1, id); stmt.setString(2, p_perm); stmt.executeUpdate(); added = true; if (logger.isDebugEnabled()) { logger.debug("Added " + p_perm + " to the table."); } } c.commit(); } catch (Exception ex) { logger.error("Failed to add permission" + p_perm + " to the database.", ex); added = false; } finally { ConnectionPool.silentClose(stmt); ConnectionPool.silentReturnConnection(c); } return added; }