Java Code Examples for java.sql.Connection.getAutoCommit()

The following are Jave code examples for showing how to use getAutoCommit() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: EvoMaster   File: SqlScriptRunner.java   View Source Code Vote up 6 votes
public static void runCommands(Connection connection, List<String> commands) {
    try {
        boolean originalAutoCommit = connection.getAutoCommit();
        try {
            if (!originalAutoCommit) {
                connection.setAutoCommit(true);
            }

            for (String command : commands) {
                execCommand(connection, command);
            }
        } finally {
            connection.setAutoCommit(originalAutoCommit);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error running script.  Cause: " + e, e);
    }
}
 
Example 2
Project: parabuild-ci   File: UpgraderToVersion17.java   View Source Code Vote up 6 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection conn, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = conn.getAutoCommit();
  Statement st = null; // NOPMD
  PreparedStatement pstmt = null; // NOPMD
  try {
    // create statement
    conn.setAutoCommit(true);
    st = conn.createStatement();

    log.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    conn.commit();

    // request post-startup config manager action
    System.setProperty(SystemConstants.SYSTEM_PROPERTY_INIT_ADVANCED_SETTINGS, "true");
  } finally {
    IoUtils.closeHard(pstmt);
    IoUtils.closeHard(st);
    conn.setAutoCommit(savedAutoCommit);
  }
}
 
Example 3
Project: aliyun-maxcompute-data-collectors   File: HCatalogTestUtils.java   View Source Code Vote up 6 votes
private void loadSqlTable(Connection conn, String table, int count,
  ColumnGenerator... extraCols) throws Exception {
  PreparedStatement statement = conn.prepareStatement(
    getSqlInsertTableStatement(table, extraCols),
    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  try {
    for (int i = 0; i < count; ++i) {
      statement.setObject(1, i, Types.INTEGER);
      statement.setObject(2, "textfield" + i, Types.VARCHAR);
      for (int j = 0; j < extraCols.length; ++j) {
        statement.setObject(j + 3, extraCols[j].getDBValue(i),
          extraCols[j].getSqlType());
      }
      statement.executeUpdate();
    }
    if (!conn.getAutoCommit()) {
      conn.commit();
    }
  } finally {
    statement.close();
  }
}
 
Example 4
Project: OftenPorter   File: DBHandleOnlyTS.java   View Source Code Vote up 6 votes
@Override
public void close() throws IOException
{
    try
    {
        Connection connection = sqlSession.getConnection();
        if (!connection.getAutoCommit())
        {
            connection.setAutoCommit(true);
        }
    } catch (SQLException e)
    {
        throw new IOException(e);
    }
    sqlSession.close();
}
 
Example 5
Project: uroborosql   File: DataSourceConnectionSupplierImpl.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 *
 * @param datasourceName 取得するコネクションのデータソース名
 *
 * @see jp.co.future.uroborosql.connection.ConnectionSupplier#getConnection(java.lang.String)
 */
@Override
public Connection getConnection(final String datasourceName) {
	try {
		DataSource ds = dsMap.computeIfAbsent(datasourceName, DataSourceConnectionSupplierImpl::getNewDataSource);
		final Connection connection;
		synchronized (ds) {
			connection = ds.getConnection();
		}
		boolean autoCommit = getAutoCommit(datasourceName);
		if (connection.getAutoCommit() != autoCommit) {
			connection.setAutoCommit(autoCommit);
		}
		boolean readOnly = getReadOnly(datasourceName);
		if (connection.isReadOnly() != readOnly) {
			connection.setReadOnly(readOnly);
		}
		int transactionIsolation = getTransactionIsolation(datasourceName);
		if (transactionIsolation > 0 && connection.getTransactionIsolation() != transactionIsolation) {
			connection.setTransactionIsolation(transactionIsolation);
		}
		return connection;
	} catch (SQLException ex) {
		throw new UroborosqlRuntimeException("Connection[" + datasourceName + "] can not be acquired.", ex);
	}
}
 
Example 6
Project: org.ops4j.pax.transx   File: ConnectionHandle.java   View Source Code Vote up 6 votes
public void rollback() throws SQLException {
    MC mc = getManagedConnection();
    if (mc.isInXaTransaction()) {
        throw new SQLException("Can not rollback within an XA transaction");
    }
    Connection c = mc.getPhysicalConnection();
    if (c.getAutoCommit()) {
        return;
    }

    try {
        LocalTransaction tx = mc.getClientLocalTransaction();
        tx.rollback();
        tx.begin();
    } catch (ResourceException e) {
        if (e.getCause() instanceof SQLException) {
            throw (SQLException) e.getCause();
        } else {
            throw new SQLException(e);
        }
    }
}
 
Example 7
Project: dble   File: UserTableInsertJob.java   View Source Code Vote up 5 votes
@Override
public void run() {
    Connection con = null;
    try {

        List<String> batch = getNextBatch();
        while (!batch.isEmpty()) {
            try {
                if (con == null || con.isClosed()) {
                    con = conPool.getConnection();
                    if (con.getAutoCommit() != autocommit) {
                        con.setAutoCommit(autocommit);
                    }
                }

                insert(con, batch);
                finshiedCount.addAndGet(batch.size());
            } catch (Exception e) {
                System.out.println("caught err in  thread :"
                        + Thread.currentThread().getId() + " " + e);
                try {
                    con.rollback();
                } catch (SQLException e1) {
                    System.out.println("caught err in thread :"
                            + Thread.currentThread().getId()
                            + " rollback err " + e1);
                }
                failedCount.addAndGet(batch.size());
            }
            batch = getNextBatch();
        }
    } finally {
        if (con != null) {
            this.conPool.returnCon(con);
        }
    }

}
 
Example 8
Project: parabuild-ci   File: DriverManagerConnectionProvider.java   View Source Code Vote up 5 votes
public Connection getConnection() throws SQLException {
	
	if ( log.isTraceEnabled() ) log.trace( "total checked-out connections: " + checkedOut );
	
	synchronized (pool) {
		if ( !pool.isEmpty() ) {
			int last = pool.size() - 1;
			if ( log.isTraceEnabled() ) {
				log.trace("using pooled JDBC connection, pool size: " + last);
				checkedOut++;
			}
			Connection pooled = (Connection) pool.remove(last);
			if (isolation!=null) pooled.setTransactionIsolation( isolation.intValue() );
			if ( pooled.getAutoCommit() ) pooled.setAutoCommit(false);
			return pooled;
		}
	}
	
	log.debug("opening new JDBC connection");
	Connection conn = DriverManager.getConnection(url, connectionProps);
	if (isolation!=null) conn.setTransactionIsolation( isolation.intValue() );
	if ( conn.getAutoCommit() ) conn.setAutoCommit(false);

	if ( log.isDebugEnabled() ) {
		log.debug( "created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation() );
	}
	if ( log.isTraceEnabled() ) checkedOut++;
	
	return conn;
}
 
Example 9
Project: parabuild-ci   File: UpgraderToVersion76.java   View Source Code Vote up 5 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection connection, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = connection.getAutoCommit();
  final Statement st = connection.createStatement();
  try {
    // create statement
    connection.setAutoCommit(true);

    LOG.debug("Altering table");
    PersistanceUtils.executeDDLs(st, new String[]{

            " alter table USERS add column DISABLE_ALL_EMAIL char(1) default 'N' not null ",
            " update USERS set DISABLE_ALL_EMAIL='N' ",
            " alter table USERS alter column DISABLE_ALL_EMAIL drop default ",
    });

    LOG.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    connection.commit();

  } finally {
    IoUtils.closeHard(st);
    connection.setAutoCommit(savedAutoCommit);
  }
}
 
Example 10
Project: parabuild-ci   File: UpgraderToVersion71.java   View Source Code Vote up 5 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection conn, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = conn.getAutoCommit();
  Statement st = null; // NOPMD
  try {
    // create statement
    conn.setAutoCommit(true);
    st = conn.createStatement();

    log.debug("Altering table");
    PersistanceUtils.executeDDLs(st, new String[]{

            " alter table MANUAL_RUN_PARAMETER add column MODIFIABLE char(1) default 'Y' not null ",
            " update MANUAL_RUN_PARAMETER set MODIFIABLE='Y' ",
            " alter table MANUAL_RUN_PARAMETER alter column MODIFIABLE drop default ",

            " alter table MANUAL_RUN_PARAMETER drop constraint MANUAL_RUN_PARAMETER_ATTRIBUTE_UC2 ",
            " alter table MANUAL_RUN_PARAMETER drop constraint MANUAL_RUN_PARAMETER_ATTRIBUTE_FC1 ",
            " drop index MANUAL_RUN_PARAMETER_IX1 ",
            " alter table MANUAL_RUN_PARAMETER add constraint MANUAL_RUN_PARAMETER_ATTRIBUTE_UC2 unique (TYPE, BUILD_ID, NAME) ",
    });

    log.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    conn.commit();

  } finally {
    IoUtils.closeHard(st);
    conn.setAutoCommit(savedAutoCommit);
  }
}
 
Example 11
Project: parabuild-ci   File: ProxoolConnectionProvider.java   View Source Code Vote up 5 votes
/**
 * Grab a connection
 * @return a JDBC connection
 * @throws SQLException
 */
public Connection getConnection() throws SQLException {
    // get a connection from the pool (thru DriverManager, cfr. Proxool doc)
	Connection c = DriverManager.getConnection(proxoolAlias);
	
	// set the Transaction Isolation if defined
	if (isolation!=null) c.setTransactionIsolation( isolation.intValue() );
	
	// toggle autoCommit to false if set
	if ( c.getAutoCommit() ) c.setAutoCommit(false);
	
	// return the connection
	return c;
}
 
Example 12
Project: parabuild-ci   File: UpgraderToVersion75.java   View Source Code Vote up 5 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection conn, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = conn.getAutoCommit();
  Statement st = null; // NOPMD
  try {
    // create statement
    conn.setAutoCommit(true);
    st = conn.createStatement();

    log.debug("Altering table");
    PersistanceUtils.executeDDLs(st, new String[]{

            " alter table AGENT add column SERIALIZE char(1) default 'N' not null ",
            " update AGENT set SERIALIZE='N' ",
            " alter table AGENT alter column SERIALIZE drop default ",
    });

    log.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    conn.commit();

  } finally {
    IoUtils.closeHard(st);
    conn.setAutoCommit(savedAutoCommit);
  }
}
 
Example 13
Project: mycat-src-1.6.1-RELEASE   File: UserTableInsertJob.java   View Source Code Vote up 5 votes
@Override
public void run() {
	Connection con = null;
	try {

		List<String> batch = getNextBatch();
		while (!batch.isEmpty()) {
			try {
				if (con == null || con.isClosed()) {
					con = conPool.getConnection();
					if (con.getAutoCommit() != autocommit) {
						con.setAutoCommit(autocommit);
					}
				}

				insert(con, batch);
				finshiedCount.addAndGet(batch.size());
			} catch (Exception e) {
				System.out.println("caught err in  thread :"
						+ Thread.currentThread().getId() + " " + e);
				try {
					con.rollback();
				} catch (SQLException e1) {
					System.out.println("caught err in thread :"
							+ Thread.currentThread().getId()
							+ " rollback err " + e1);
				}
				failedCount.addAndGet(batch.size());
			}
			batch = getNextBatch();
		}
	} finally {
		if (con != null) {
			this.conPool.returnCon(con);
		}
	}

}
 
Example 14
Project: parabuild-ci   File: UpgraderToVersion67.java   View Source Code Vote up 5 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection conn, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = conn.getAutoCommit();
  Statement st = null; // NOPMD
  try {
    // create statement
    conn.setAutoCommit(true);
    st = conn.createStatement();

    LOG.debug("Altering table");
    PersistanceUtils.executeDDLs(st, new String[]{
      //
      " alter table PROMOTION_STEP add column LINE_NUMBER integer default 0 not null ",
      " update PROMOTION_STEP set LINE_NUMBER=ID ",
      " alter table PROMOTION_STEP alter column LINE_NUMBER drop default ",
      " create index PROMOTION_STEP_IX1 on PROMOTION_STEP(PROMOTION_POLICY_ID, LINE_NUMBER) ",
    });

    LOG.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    conn.commit();

    // request post-startup config manager action
    System.setProperty(SystemConstants.SYSTEM_PROPERTY_INIT_ADVANCED_SETTINGS, "true");
  } finally {
    IoUtils.closeHard(st);
    conn.setAutoCommit(savedAutoCommit);
  }
}
 
Example 15
Project: org.ops4j.pax.transx   File: ConnectionHandle.java   View Source Code Vote up 5 votes
public void setAutoCommit(boolean autoCommit) throws SQLException {
    MC mc = getManagedConnection();
    if (mc.isInXaTransaction()) {
        throw new SQLException("Can not set autoCommit within an XA transaction");
    }
    Connection c = mc.getPhysicalConnection();
    if (autoCommit == c.getAutoCommit()) {
        // nothing to do
        return;
    }

    try {
        LocalTransaction tx = mc.getClientLocalTransaction();
        if (autoCommit) {
            // reenabling autoCommit - JDBC spec says current transaction is committed
            tx.commit();
        } else {
            // disabling autoCommit
            tx.begin();
        }
    } catch (ResourceException e) {
        if (e.getCause() instanceof SQLException) {
            throw (SQLException) e.getCause();
        } else {
            throw new SQLException(e);
        }
    }
}
 
Example 16
Project: s-store   File: ConnectionDefaults.java   View Source Code Vote up 5 votes
public ConnectionDefaults(Connection connection) throws SQLException {

        this.holdability          = connection.getHoldability();
        this.transactionIsolation = connection.getTransactionIsolation();
        this.isAutoCommit         = connection.getAutoCommit();
        this.isReadOnly           = connection.isReadOnly();
        this.catalog              = connection.getCatalog();
    }
 
Example 17
Project: parabuild-ci   File: UpgraderToVersion72.java   View Source Code Vote up 4 votes
/**
 * Perform upgrade.
 */
public void upgrade(final Connection conn, final int upgradeToVersion) throws SQLException {
  final boolean savedAutoCommit = conn.getAutoCommit();
  Statement st = null; // NOPMD
  try {
    // create statement
    conn.setAutoCommit(true);
    st = conn.createStatement();

    LOG.debug("Altering table");
    PersistanceUtils.executeDDLs(st, new String[]{
            //
            // LICENSE_USE table
            //
            "create cached table LICENSE_USE (" +
                    "    ID integer not null identity," +
                    "    SAMPLE_DAY datetime not null," +
                    "    DAY_USE_COUNT int not null," +
                    "    MEDIAN_USE_COUNT int not null," +
                    "    EXEEDED_COUNT int not null," +
                    "    LICENSED_NUMBER int not null," +
                    "    constraint LICENSE_USE_UC1 unique (ID)," +
                    "    constraint LICENSE_USE_UC2 unique (SAMPLE_DAY)" +
                    ')',
            //
            // COMMENT table
            //
            "create cached table COMMENT (" +
                    "    ID integer not null identity," +
                    "    OWNER_TYPE tinyint not null," +
                    "    OWNER_ID int not null," +
                    "    COMMENT_TIME datetime not null," +
                    "    COMMENT_TYPE tinyint not null," +
                    "    AUTHOR_ID int not null," +
                    "    RESPONCE_TO_ID int not null," +
                    "    constraint COMMENT_UC1 unique (ID)," +
                    "    constraint COMMENT_FC1 foreign key (AUTHOR_ID) references USERS(ID)" +
                    ')',
            "create index COMMENT_IX1 on COMMENT(OWNER_TYPE, OWNER_ID, COMMENT_TIME)"
    });

    LOG.debug("Updating version");
    st.executeUpdate("update SYSTEM_PROPERTY set VALUE = '" + upgraderVersion() + "' where NAME = 'parabuild.schema.version' ");

    // finish
    conn.commit();

    // request post-startup config manager action
    System.setProperty(SystemConstants.SYSTEM_PROPERTY_INIT_RETRY_SETTINGS, "true");
  } finally {
    IoUtils.closeHard(st);
    conn.setAutoCommit(savedAutoCommit);
  }
}
 
Example 18
Project: apache-tomcat-7.0.73-with-comment   File: CreateTestTable.java   View Source Code Vote up 4 votes
@Test
public void testPopulateData() throws Exception {
    int count = 100000;
    int actual = testCheckData();
    if (actual>=count) {
        System.out.println("Test tables has "+actual+" rows of data. No need to populate.");
        return;
    }

    datasource.setJdbcInterceptors(ResetAbandonedTimer.class.getName());
    String insert = "insert into test values (?,?,?,?,?)";
    this.datasource.setRemoveAbandoned(false);
    Connection con = datasource.getConnection();

    boolean commit = con.getAutoCommit();
    con.setAutoCommit(false);
    if (recreate) {
        Statement st = con.createStatement();
        try {
            st.execute("drop table test");
        }catch (Exception ignore) {}
        st.execute("create table test(id int not null, val1 varchar(255), val2 varchar(255), val3 varchar(255), val4 varchar(255))");
        st.close();
    }


    PreparedStatement ps = con.prepareStatement(insert);
    ps.setQueryTimeout(0);
    for (int i=actual; i<count; i++) {
        ps.setInt(1,i);
        String s = getRandom();
        ps.setString(2, s);
        ps.setString(3, s);
        ps.setString(4, s);
        ps.setString(5, s);
        ps.addBatch();
        ps.clearParameters();
        if ((i+1) % 1000 == 0) {
            System.out.print(".");
        }
        if ((i+1) % 10000 == 0) {
            System.out.print("\n"+(i+1));
            ps.executeBatch();
            ps.close();
            con.commit();
            ps = con.prepareStatement(insert);
            ps.setQueryTimeout(0);
        }

    }
    ps.close();
    con.setAutoCommit(commit);
    con.close();
}
 
Example 19
Project: lams   File: JdbcMigrationLauncher.java   View Source Code Vote up 4 votes
/**
 * Performs the application rollbacks
 *
 * @param context       the database context to run the patches in
 * @param rollbackLevel the level the system should rollback to
 * @param forceRollback is a boolean indicating if the application should ignore a check to see if all patches are rollbackable
 * @return the number of patches applied
 * @throws SQLException       if an unrecoverable database error occurs while working with the patches table.
 * @throws MigrationException if an unrecoverable error occurs during the migration
 */
public int doRollbacks(JdbcMigrationContext context, int[] rollbackLevel, boolean forceRollback)
        throws SQLException, MigrationException
{
    PatchInfoStore patchTable = createPatchStore(context);

    lockPatchStore(context);

    // Now apply the patches
    int executedPatchCount = 0;
    try
    {

        // remember the auto-commit state, and turn auto-commit off
        Connection conn = context.getConnection();
        boolean commitState = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // run the rollbacks
        try
        {
            executedPatchCount = migrationProcess.doRollbacks(patchTable, rollbackLevel, context, forceRollback);
        }

        // restore autocommit state
        finally
        {
            if ((conn != null) && !conn.isClosed())
            {
                conn.setAutoCommit(commitState);
            }
        }
    }
    catch (MigrationException me)
    {
        // If there was any kind of error, we don't want to eat it, but we do
        // want to unlock the patch store. So do that, then re-throw.
        patchTable.unlockPatchStore();
        throw me;
    }

    // Do any post-patch tasks
    try
    {
        migrationProcess.doPostPatchMigrations(context);
        return executedPatchCount;
    }
    finally
    {
        try
        {
            patchTable.unlockPatchStore();
        }
        catch (MigrationException e)
        {
            log.error("Error unlocking patch table: ", e);
        }
    }
}
 
Example 20
Project: calcite-avatica   File: ConnectionPropertiesImpl.java   View Source Code Vote up 4 votes
public ConnectionPropertiesImpl(Connection conn) throws SQLException {
  this(conn.getAutoCommit(), conn.isReadOnly(), conn.getTransactionIsolation(),
      conn.getCatalog(), conn.getSchema());
}