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:edu.umd.cs.submitServer.servlets.ReportTestOutcomes.java

/**
 * @param conn//from   w ww . java 2s . c o m
 * @return
 * @throws SQLException
 */
private Connection switchToTransaction(Connection conn) throws SQLException {
    conn.close();
    // Begin a transaction.
    // We can set this to a low isolation level because
    // - We don't read anything
    // - The inserts/updates we perform should not affect
    // rows visible to any other transaction
    conn = getConnection();
    conn.setAutoCommit(false);
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    return conn;
}

From source file:com.cws.esolutions.core.dao.impl.ServerDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServerDataDAO#addServer(java.util.List)
 *///ww w  .  j  a  va2s .  c o m
public synchronized boolean addServer(final List<Object> serverData) throws SQLException {
    final String methodName = IServerDataDAO.CNAME
            + "#addServer(final List<Object> serverData) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);

        for (Object str : serverData) {
            DEBUGGER.debug("Value: {}", str);
        }
    }

    Connection sqlConn = null;
    boolean isComplete = false;
    CallableStatement stmt = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall(
                "{CALL insertNewServer(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}");
        stmt.setString(1, (String) serverData.get(0)); // systemGuid
        stmt.setString(2, (String) serverData.get(1)); // systemOs
        stmt.setString(3, (String) serverData.get(2)); // systemStatus
        stmt.setString(4, (String) serverData.get(3)); // systemRegion
        stmt.setString(5, (String) serverData.get(4)); // networkPartiton
        stmt.setString(6, (String) serverData.get(5)); // datacenter
        stmt.setString(7, (String) serverData.get(6)); // systemType
        stmt.setString(8, (String) serverData.get(7)); // domainName
        stmt.setString(9, (String) serverData.get(8)); // cpuType
        stmt.setInt(10, (Integer) serverData.get(9)); // cpuCount
        stmt.setString(11, (String) serverData.get(10)); // serverModel
        stmt.setString(12, (String) serverData.get(11)); // serialNumber
        stmt.setInt(13, (Integer) serverData.get(12)); // installedMemory
        stmt.setString(14, (String) serverData.get(13)); // operIp
        stmt.setString(15, (String) serverData.get(14)); // operHostname
        stmt.setString(16, (String) serverData.get(15)); // mgmtIp
        stmt.setString(17, (String) serverData.get(16)); // mgmtHostname
        stmt.setString(18, (String) serverData.get(17)); // backupIp
        stmt.setString(19, (String) serverData.get(18)); // backupHostname
        stmt.setString(20, (String) serverData.get(19)); // nasIp
        stmt.setString(21, (String) serverData.get(20)); // nasHostname
        stmt.setString(22, (String) serverData.get(21)); // natAddr
        stmt.setString(23, (String) serverData.get(22)); // systemComments
        stmt.setString(24, (String) serverData.get(23)); // engineer
        stmt.setString(25, (String) serverData.get(24)); // mgrEntry
        stmt.setInt(26, (Integer) serverData.get(25)); // dmgrPort
        stmt.setString(27, (String) serverData.get(26)); // serverRack
        stmt.setString(28, (String) serverData.get(27)); // rackPosition
        stmt.setString(29, (String) serverData.get(28)); // owningDmgr

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        isComplete = (!(stmt.execute()));

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return isComplete;
}

From source file:com.wso2telco.dep.mediator.dao.USSDDAO.java

public void moUssdSubscriptionDelete(Integer moSubscriptionId) throws SQLException, Exception {

    Connection con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
    PreparedStatement deleteSubscriptionsStatement = null;
    PreparedStatement deleteOperatorSubscriptionsStatement = null;

    try {//  ww  w. ja  va2  s  .  c  o m

        if (con == null) {

            throw new Exception("Connection not found");
        }

        /**
         * Set autocommit off to handle the transaction
         */
        con.setAutoCommit(false);

        StringBuilder deleteSubscriptionsQueryString = new StringBuilder("DELETE FROM ")
                .append(DatabaseTables.USSD_REQUEST_ENTRY.getTableName()).append(" WHERE ussd_request_did = ?");

        deleteSubscriptionsStatement = con.prepareStatement(deleteSubscriptionsQueryString.toString());
        deleteSubscriptionsStatement.setInt(1, moSubscriptionId);

        log.debug("sql query in outboundSubscriptionDelete : " + deleteSubscriptionsStatement);

        deleteSubscriptionsStatement.executeUpdate();

        StringBuilder deleteOperatorSubscriptionsQueryString = new StringBuilder("DELETE FROM ")
                .append(DatabaseTables.MO_USSD_SUBSCRIPTIONS.getTableName())
                .append(" WHERE ussd_request_did = ?");

        deleteOperatorSubscriptionsStatement = con
                .prepareStatement(deleteOperatorSubscriptionsQueryString.toString());

        deleteOperatorSubscriptionsStatement.setInt(1, moSubscriptionId);

        log.debug("sql query in outboundSubscriptionDelete : " + deleteOperatorSubscriptionsStatement);

        deleteOperatorSubscriptionsStatement.executeUpdate();

        /**
         * commit the transaction if all success
         */
        con.commit();
    } catch (SQLException e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("database operation error in moUssdSubscriptionDelete : ", e);
        throw e;
    } catch (Exception e) {

        /**
         * rollback if Exception occurs
         */
        con.rollback();

        log.error("Error while deleting subscriptions. ", e);
        throw e;
    } finally {

        DbUtils.closeAllConnections(deleteSubscriptionsStatement, con, null);
        DbUtils.closeAllConnections(deleteOperatorSubscriptionsStatement, null, null);
    }
}

From source file:com.cws.esolutions.core.dao.impl.ServerDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServerDataDAO#updateServer(java.lang.String, java.util.List)
 *///www .  ja va 2s  .  c  o  m
public synchronized boolean updateServer(final String serverGuid, final List<Object> serverData)
        throws SQLException {
    final String methodName = IServerDataDAO.CNAME
            + "#updateServer(final String serverGuid, final List<Object> serverData) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", serverGuid);

        for (Object str : serverData) {
            DEBUGGER.debug("Value: {}", str);
        }
    }

    Connection sqlConn = null;
    boolean isComplete = false;
    CallableStatement stmt = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall(
                "{CALL updateServerData(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}");
        stmt.setString(1, serverGuid); // systemGuid
        stmt.setString(2, (String) serverData.get(1)); // systemOs
        stmt.setString(3, (String) serverData.get(2)); // systemStatus
        stmt.setString(4, (String) serverData.get(3)); // systemRegion
        stmt.setString(5, (String) serverData.get(4)); // networkPartiton
        stmt.setString(6, (String) serverData.get(5)); // datacenter
        stmt.setString(7, (String) serverData.get(6)); // systemType
        stmt.setString(8, (String) serverData.get(7)); // domainName
        stmt.setString(9, (String) serverData.get(8)); // cpuType
        stmt.setInt(10, (Integer) serverData.get(9)); // cpuCount
        stmt.setString(11, (String) serverData.get(10)); // serverModel
        stmt.setString(12, (String) serverData.get(11)); // serialNumber
        stmt.setInt(13, (Integer) serverData.get(12)); // installedMemory
        stmt.setString(14, (String) serverData.get(13)); // operIp
        stmt.setString(15, (String) serverData.get(14)); // operHostname
        stmt.setString(16, (String) serverData.get(15)); // mgmtIp
        stmt.setString(17, (String) serverData.get(16)); // mgmtHostname
        stmt.setString(18, (String) serverData.get(17)); // backupIp
        stmt.setString(19, (String) serverData.get(18)); // backupHostname
        stmt.setString(20, (String) serverData.get(19)); // nasIp
        stmt.setString(21, (String) serverData.get(20)); // nasHostname
        stmt.setString(22, (String) serverData.get(21)); // natAddr
        stmt.setString(23, (String) serverData.get(22)); // systemComments
        stmt.setString(24, (String) serverData.get(23)); // engineer
        stmt.setString(25, (String) serverData.get(24)); // mgrEntry
        stmt.setInt(26, (Integer) serverData.get(25)); // dmgrPort
        stmt.setString(27, (String) serverData.get(26)); // serverRack
        stmt.setString(28, (String) serverData.get(27)); // rackPosition
        stmt.setString(29, (String) serverData.get(28)); // owningDmgr

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        isComplete = (!(stmt.execute()));

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return isComplete;
}

From source file:hoot.services.db.DbUtils.java

public static void deleteOSMRecordByName(Connection conn, String mapName) throws Exception {
    try {//from www.j  av  a  2  s  . c  o  m
        Configuration configuration = getConfiguration();

        QMaps maps = QMaps.maps;
        List<Long> mapIds = new SQLQuery(conn, configuration).from(maps)
                .where(maps.displayName.equalsIgnoreCase(mapName)).list(maps.id);

        if (mapIds.size() > 0) {
            Long mapId = mapIds.get(0);
            deleteMapRelatedTablesByMapId(mapId);

            conn.setAutoCommit(false);

            ListSubQuery<Long> res = new SQLSubQuery().from(maps)
                    .where(maps.displayName.equalsIgnoreCase(mapName)).list(maps.id);

            new SQLDeleteClause(conn, configuration, maps).where(maps.displayName.eq(mapName)).execute();

            QReviewItems reviewItems = QReviewItems.reviewItems;
            new SQLDeleteClause(conn, configuration, reviewItems).where(reviewItems.mapId.in(res)).execute();

            QElementIdMappings elementIdMappings = QElementIdMappings.elementIdMappings;
            new SQLDeleteClause(conn, configuration, elementIdMappings).where(elementIdMappings.mapId.in(res))
                    .execute();

            QReviewMap reviewMap = QReviewMap.reviewMap;
            new SQLDeleteClause(conn, configuration, reviewMap).where(reviewMap.mapId.in(res)).execute();

            conn.commit();
        }
    } catch (Exception e) {
        String msg = "Error deleting OSM record.  ";
        if (e.getCause() instanceof BatchUpdateException) {
            BatchUpdateException batchException = (BatchUpdateException) e.getCause();
            msg += "  " + batchException.getNextException().getMessage();
        }
        throw new Exception(msg);
    }
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public void updateRecord(Object object, String keyFieldName) throws SQLException, WPBSerializerException {
    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    try {//www .j  a  va2 s  .  com
        Set<String> ignoreFields = new HashSet<String>();
        ignoreFields.add(keyFieldName);

        String sqlStatement = getSQLStringForUpdate(object, keyFieldName);
        connection.setAutoCommit(true);
        preparedStatement = connection.prepareStatement(sqlStatement);
        int fieldsCount = buildStatementForInsertUpdate(object, ignoreFields, preparedStatement, connection);
        Object keyValue = getObjectProperty(object, keyFieldName);
        setPrepareStatementParameter(preparedStatement, fieldsCount + 1, keyValue);

        preparedStatement.execute();
    } catch (SQLException e) {
        throw e;
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        connection.close();
    }
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public <T> T addRecord(T object, String keyFieldName) throws SQLException, WPBSerializerException {
    Connection connection = getConnection();
    PreparedStatement preparedStatement = null;
    try {/* ww w .  ja v a 2 s  .  c  o  m*/
        Set<String> ignoreFields = new HashSet<String>();
        ignoreFields.add(keyFieldName);
        String sqlStatement = getSQLStringForInsert(object, ignoreFields);
        connection.setAutoCommit(true);
        preparedStatement = connection.prepareStatement(sqlStatement);
        buildStatementForInsertUpdate(object, ignoreFields, preparedStatement, connection);
        preparedStatement.execute();
        ResultSet resultKey = preparedStatement.getGeneratedKeys();
        if (resultKey.next()) {
            Long key = resultKey.getLong(1);
            setObjectProperty(object, keyFieldName, key);
        }
        return object;
    } catch (SQLException e) {
        throw e;
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        connection.close();
    }
}

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

@Before
public void setUp() {
    super.setUp();

    SqoopOptions options = new SqoopOptions(CONNECT_STRING, TABLE_NAME);
    options.setUsername(DATABASE_USER);//  ww  w . j a v  a2 s  .  c  o  m
    options.setPassword(DATABASE_PASSWORD);

    manager = new SQLServerManager(options);

    // Drop the existing table, if there is one.
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = manager.getConnection();
        stmt = conn.createStatement();
        stmt.execute("DROP TABLE " + TABLE_NAME);
    } catch (SQLException sqlE) {
        LOG.info("Table was not dropped: " + sqlE.getMessage());
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
        } catch (Exception ex) {
            LOG.warn("Exception while closing stmt", ex);
        }
    }

    // Create and populate table
    try {
        conn = manager.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        // create the database table and populate it with data.
        stmt.executeUpdate(
                "CREATE TABLE " + TABLE_NAME + " (" + "id INT NOT NULL, " + "name VARCHAR(24) NOT NULL, "
                        + "salary FLOAT, " + "dept VARCHAR(32), " + "PRIMARY KEY (id))");

        stmt.executeUpdate(
                "INSERT INTO " + TABLE_NAME + " VALUES(" + "1,'Aaron', " + "1000000.00,'engineering')");
        stmt.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "2,'Bob', " + "400.00,'sales')");
        stmt.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "3,'Fred', 15.00," + "'marketing')");
        conn.commit();
    } catch (SQLException sqlE) {
        LOG.error("Encountered SQL Exception: ", sqlE);
        sqlE.printStackTrace();
        fail("SQLException when running test setUp(): " + sqlE);
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
        } catch (Exception ex) {
            LOG.warn("Exception while closing connection/stmt", ex);
        }
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java

/**
 * Create a ExtendedFieldValue in persistent storage.
 * @param aConnection an open connection to the HarvestDatabase.
 * @param aExtendedFieldValue The ExtendedFieldValue to create in 
 *  persistent storage//from   w  w w. j  ava  2 s .co  m
 * @param aCommit Should we commit this or not
 * @throws SQLException In case of Database access problems.
 */
public void create(Connection aConnection, ExtendedFieldValue aExtendedFieldValue, boolean aCommit)
        throws SQLException {
    ArgumentNotValid.checkNotNull(aExtendedFieldValue, "aExtendedFieldValue");

    if (aExtendedFieldValue.getExtendedFieldValueID() != null) {
        log.warn("The extendedFieldValueID for this extendedField Value "
                + "is already set. This should probably never happen.");
    } else {
        aExtendedFieldValue.setExtendedFieldValueID(generateNextID(aConnection));
    }

    log.debug("Creating " + aExtendedFieldValue.toString());

    PreparedStatement statement = null;
    aConnection.setAutoCommit(false);
    statement = aConnection.prepareStatement("" + "INSERT INTO extendedfieldvalue "
            + "            (extendedfieldvalue_id, " + "             extendedfield_id, "
            + "             content, " + "             instance_id) " + "VALUES      (?, " + "             ?, "
            + "             ?, " + "             ?) ");

    statement.setLong(1, aExtendedFieldValue.getExtendedFieldValueID());
    statement.setLong(2, aExtendedFieldValue.getExtendedFieldID());
    statement.setString(3, aExtendedFieldValue.getContent());
    statement.setLong(4, aExtendedFieldValue.getInstanceID());

    statement.executeUpdate();
    if (aCommit) {
        aConnection.commit();
    }
}