Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection setAutoCommit.

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.cloudera.sqoop.manager.OracleUtils.java

/**
 * Drop a table if it exists./*from  w  w  w  .  j  a  v a2  s.c  o m*/
 */
public static void dropTable(String tableName, ConnManager manager) throws SQLException {
    Connection connection = null;
    Statement st = null;

    try {
        connection = manager.getConnection();
        connection.setAutoCommit(false);
        st = connection.createStatement();

        // create the database table and populate it with data.
        st.executeUpdate(getDropTableStatement(tableName));

        connection.commit();
    } finally {
        try {
            if (null != st) {
                st.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("Got SQLException when closing connection: " + sqlE);
        }
    }
}

From source file:com.sf.ddao.TxHelper.java

public static <T, SK> T execInTx(TransactionableDao<SK> dao, Callable<T> callable, SK... shardKeys)
        throws Exception {
    Context context = dao.startTransaction(shardKeys == null || shardKeys.length == 0 ? null : shardKeys[0]);
    boolean success = false;
    Connection conn;
    try {//from  www . j a  v  a 2  s  . c  om
        conn = ConnectionHandlerHelper.getConnectionOnHold(context);
        connectionOnHold.set(conn);
        conn.setAutoCommit(false);
        T res = callable.call();
        conn.commit();
        success = true;
        return res;
    } finally {
        connectionOnHold.remove();
        conn = ConnectionHandlerHelper.releaseConnectionOnHold(context);
        if (!success) {
            conn.rollback();
        }
        conn.close();
    }
}

From source file:com.pinterest.deployservice.db.DatabaseUtil.java

public static void transactionalUpdate(BasicDataSource dataSource, List<UpdateStatement> updateStatements)
        throws Exception {
    QueryRunner queryRunner = new QueryRunner();
    Connection connection = dataSource.getConnection();
    boolean autoStatus = connection.getAutoCommit();
    connection.setAutoCommit(false);
    try {/*  w ww . java2 s.  com*/
        for (UpdateStatement updateStatement : updateStatements) {
            queryRunner.update(connection, updateStatement.getStatement(), updateStatement.getValueArray());
        }
        connection.commit();
    } catch (SQLException e) {
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(autoStatus);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.paladin.sys.db.DBManager.java

/**
 * /*from  w  ww  . j ava2s.  c  om*/
 */
public static final void closeConnection() {
    Connection conn = conns.get();
    try {
        if (conn != null && !conn.isClosed()) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (SQLException e) {
        log.error("Unable to close connection!!! ", e);
    }
    conns.set(null);
}

From source file:com.aurel.track.dbase.Migrate416To417.java

/**
 * Add the document and document section
 * Use JDBC because negative objectIDs should be added
 *///from  w  w w .  j a v  a  2 s .c  o m
public static void addDeletedBasket() {
    TBasketBean basketBean = BasketBL.getBasketByID(TBasketBean.BASKET_TYPES.DELETED);
    if (basketBean == null) {
        LOGGER.info("Add 'Deleted basket' basket");
        Connection cono = null;
        try {
            cono = InitDatabase.getConnection();
            Statement ostmt = cono.createStatement();
            cono.setAutoCommit(false);
            String deletedBasketStmt = addDeletedBasketStmt(TBasketBean.BASKET_TYPES.DELETED, "basket.label.-1",
                    "-1001");
            ostmt.executeUpdate(deletedBasketStmt);
            cono.commit();
            cono.setAutoCommit(true);
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(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.aurel.track.dbase.Migrate415To416.java

/**
 * Add the document and document section
 * Use JDBC because negative objectIDs should be added
 *///from   w w  w  .j  ava  2 s . c o m
public static void addNewItemTypes() {
    LOGGER.info("Add new item types");
    List<String> itemTypeStms = new ArrayList<String>();
    TListTypeBean docIssueTypeBean = IssueTypeBL.loadByPrimaryKey(-6);
    if (docIssueTypeBean == null) {
        LOGGER.info("Add 'Document folder' item type");
        itemTypeStms.add(addItemtype(-6, "Document folder", 6, -6, "documentFolder.png", "2009"));
    }

    Connection cono = null;
    try {
        cono = InitDatabase.getConnection();
        Statement ostmt = cono.createStatement();
        cono.setAutoCommit(false);
        for (String filterClobStmt : itemTypeStms) {
            ostmt.executeUpdate(filterClobStmt);
        }
        cono.commit();
        cono.setAutoCommit(true);
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(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));
        }
    }
    //children types
    List<TChildIssueTypeBean> childIssueTypeBeans = ChildIssueTypeAssignmentsBL
            .loadByChildAssignmentsByParent(-6);
    if (childIssueTypeBeans == null || childIssueTypeBeans.isEmpty()) {
        //document may have only document section children
        ChildIssueTypeAssignmentsBL.save(-6, -4);
    }
}

From source file:io.apiman.gateway.engine.jdbc.JdbcMetricsTest.java

/**
 * Creates an in-memory datasource.//w w w  .  jav  a2s.c  o  m
 * @throws SQLException
 */
private static BasicDataSource createInMemoryDatasource() throws Exception {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    Connection connection = ds.getConnection();
    connection.setAutoCommit(true);
    initDB(connection);
    connection.close();
    return ds;
}

From source file:com.aurel.track.dbase.Migrate500To502.java

/**
 * Add inline linked link type/*  w  ww  .j  a  va  2s. c o m*/
 */
static void addInlineLinkedLinkType() {
    List<TLinkTypeBean> inlinelinkTypeBeans = LinkTypeBL
            .loadByLinkType(InlineLinkType.getInstance().getPluginID(), null);
    if (inlinelinkTypeBeans == null || inlinelinkTypeBeans.isEmpty()) {
        TLinkTypeBean linkTypeBean = LinkTypeBL.loadByPrimaryKey(13);
        if (linkTypeBean == null) {
            LOGGER.info("Add 'inline linked' link type with fixed ID");
            Connection cono = null;
            try {
                cono = InitDatabase.getConnection();
                Statement ostmt = cono.createStatement();
                cono.setAutoCommit(false);
                String inlineLinkTypeStmt = addInlineLinkTypeStmt(13, "is inline linked in",
                        "the filtered items are inline linked to", LINK_DIRECTION.RIGHT_TO_LEFT,
                        InlineLinkType.class.getName(), "0123456789");
                ostmt.executeUpdate(inlineLinkTypeStmt);
                cono.commit();
                cono.setAutoCommit(true);
            } catch (Exception e) {
                LOGGER.debug(ExceptionUtils.getStackTrace(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));
                }
            }
        } else {
            LOGGER.info("Add 'inline linked' link type at end");
            UpgradeDatabase.addLinkType("is inline linked in", "the filtered items are inline linked to",
                    LINK_DIRECTION.RIGHT_TO_LEFT, InlineLinkType.class.getName());
        }
    }
}

From source file:io.undertow.js.test.jdbc.JavascriptJDBCWrapperTestCase.java

@BeforeClass
public static void setup() throws Exception {
    ds = JdbcConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "user", "password");

    Connection conn = null;
    Statement statement = null;/*from   www.j  a  v a  2s . co  m*/
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(true);
        statement = conn.createStatement();
        statement.executeUpdate("CREATE TABLE PUBLIC.CUSTOMER (" + " id SERIAL NOT NULL,"
                + " first VARCHAR(255) NOT NULL," + " last VARCHAR(255)," + " PRIMARY KEY (id)" + " );");
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (conn != null) {
            conn.close();
        }

    }

    js = UndertowJS.builder().addInjectionProvider(new TestDatabaseInjection())
            .addResources(new ClassPathResourceManager(JavascriptJDBCWrapperTestCase.class.getClassLoader(),
                    JavascriptJDBCWrapperTestCase.class.getPackage()), "jdbc.js")
            .build();
    js.start();
    DefaultServer.setRootHandler(js.getHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send("Default Response");
        }
    }));
}

From source file:com.medlog.webservice.util.ToneAnalyzerExample.java

public static void processTone(DbConnection dbc, ToneAnalysis tone, int diaryID) {
    CallableStatement cs = null;/*w ww .jav  a  2s.  c  o m*/
    String cat_id = "";
    try {
        //category , tone , sentance,score,text
        List<ToneCategory> to = tone.getDocumentTone().getTones();
        Connection conn = dbc.getConnnection();

        conn.prepareCall(new StringBuilder().append("{call spDiaryTextScoreInsert(").append(diaryID)
                .append(",?,?,?,?,?)}").toString());
        conn.setAutoCommit(false);
        cs.setInt(3, 0);
        cs.setNull(5, java.sql.Types.NVARCHAR);// cat_id);

        for (ToneCategory docTC : to) {
            cat_id = docTC.getId();
            cs.setString(1, cat_id);
            for (ToneScore s : docTC.getTones()) {
                cs.setString(2, s.getId());
                cs.setDouble(4, s.getScore());
                cs.addBatch();
            }
            int[] docRes = cs.executeBatch();
            cs.clearBatch();
            System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result --- "
                    + ArrayUtils.toString(docRes));
        }
        System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() Process "
                + tone.getSentencesTone().size() + " sentances.");
        for (SentenceTone sentT : tone.getSentencesTone()) {
            to = sentT.getTones();
            cs.setInt(3, sentT.getId());
            cs.setString(5, toS(sentT.getText()).trim());
            for (ToneCategory docTC : to) {
                cat_id = docTC.getId();
                cs.setString(1, cat_id);
                for (ToneScore s : docTC.getTones()) {
                    cs.setString(2, s.getId());
                    cs.setDouble(4, s.getScore());
                    cs.addBatch();
                }
                int[] docRes = cs.executeBatch();
                cs.clearBatch();
                System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result["
                        + sentT.getId() + "] " + ArrayUtils.toString(docRes));
            }
        }

    } catch (SQLException ex) {
        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
    }
}