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.cws.esolutions.security.dao.userauth.impl.SQLAuthenticator.java

/**
 * @see com.cws.esolutions.security.dao.userauth.interfaces.Authenticator#verifySecurityData(java.lang.String, java.lang.String, java.util.List)
 *///w  ww.j  a v  a  2  s. co  m
public synchronized boolean verifySecurityData(final String userId, final String userGuid,
        final List<String> attributes) throws AuthenticatorException {
    final String methodName = SQLAuthenticator.CNAME
            + "#verifySecurityData(final String userId, final String userGuid, final List<String> attributes) throws AuthenticatorException";

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

    Connection sqlConn = null;
    CallableStatement stmt = null;

    try {
        sqlConn = SQLAuthenticator.dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL verifySecurityQuestions(?, ?, ?, ?)}");
        stmt.setString(1, userGuid); // guid
        stmt.setString(2, userId);
        stmt.setString(3, attributes.get(0)); // username
        stmt.setString(4, attributes.get(1)); // username

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

        return stmt.execute();
    } catch (SQLException sqx) {
        throw new AuthenticatorException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new AuthenticatorException(sqx.getMessage(), sqx);
        }
    }
}

From source file:com.spvp.dal.MySqlDatabase.java

@Override
public Boolean ucitajPrognozeUBazu(ArrayList<Prognoza> prognoze) throws SQLException {

    Connection conn = null;
    Boolean status = false;//from  w  w w.ja v  a  2s.  c o m

    try {
        conn = getConnection();
        conn.setAutoCommit(false);

        Statement s = conn.createStatement();
        ResultSet rs = s.executeQuery("SELECT AUTO_INCREMENT " + "FROM  INFORMATION_SCHEMA.TABLES "
                + "WHERE TABLE_SCHEMA = 'weather_forecasting' " + "AND   TABLE_NAME   = 'historija_prognoze';");

        int zadnjiId = -1;

        rs.next();
        zadnjiId = rs.getInt("AUTO_INCREMENT");

        int idGrada = -1;

        PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO historija_prognoze (id, vrijeme, temp, pritisak, brzina_vjetra, vlaznost_zraka, datum) "
                        + "VALUES(?, ?,?,?,?,?,?)");

        PreparedStatement pstmt3 = conn
                .prepareStatement("INSERT INTO gradovi_prognoze (prognoza_id, grad_id) " + "VALUES(?,?)");

        for (Prognoza x : prognoze) {

            pstmt.clearParameters();
            pstmt.setInt(1, zadnjiId);
            pstmt.setString(2, x.getVrijeme());
            pstmt.setString(3, x.getTemperatura());
            pstmt.setString(4, x.getPritisakZraka());
            pstmt.setString(5, x.getBrzinaVjetra());
            pstmt.setString(6, x.getVlaznostZraka());
            pstmt.setDate(7, new java.sql.Date(x.getDatum().getTime()));
            pstmt.addBatch();

            idGrada = dajIdGradaPoImenu(x.getZaGrad().getImeGrada());

            pstmt3.clearParameters();
            pstmt3.setInt(1, zadnjiId);
            pstmt3.setInt(2, idGrada);

            pstmt3.addBatch();

            zadnjiId++;
        }

        pstmt.executeBatch();
        pstmt3.executeBatch();

        conn.commit();
        status = true;

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
        if (conn != null)
            conn.rollback();

    } finally {

        if (conn != null)
            conn.close();
    }

    return status;
}

From source file:com.trackplus.ddl.DataWriter.java

private static int executeScript(String fileName, Connection con, String endOfStatement) throws DDLException {
    BufferedReader bufferedReader = createBufferedReader(fileName);

    String line;//from   www  .j  a  v  a 2  s  .co m
    StringBuilder sql = new StringBuilder();

    Statement stmt = MetaDataBL.createStatement(con);

    int idx = 0;
    try {
        while ((line = bufferedReader.readLine()) != null) {
            sql.append(line);
            if (line.endsWith(endOfStatement)) {
                String s = sql.substring(0, sql.length() - endOfStatement.length());
                idx++;
                if (idx % 5000 == 0) {
                    LOGGER.info(idx + " inserts executed...");
                }
                executeUpdate(con, stmt, s);
                sql.setLength(0);
            } else {
                sql.append("\n");
            }
        }
    } catch (IOException e) {
        throw new DDLException(e.getMessage(), e);
    }

    //close file
    try {
        bufferedReader.close();
    } catch (IOException e) {
        throw new DDLException(e.getMessage(), e);
    }

    //close connection
    try {
        stmt.close();
        con.commit();
        con.setAutoCommit(true);
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }

    return idx;
}

From source file:com.atolcd.alfresco.repo.patch.SchemaUpgradeScriptPatch.java

public Object doWork() throws Exception {

    Connection connection = null;
    try {//from   w  w w .  j  a va  2s. c om
        // make sure that we AUTO-COMMIT
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);

        Configuration cfg = localSessionFactory.getConfiguration();

        // check if the script was successfully executed
        boolean wasSuccessfullyApplied = didPatchSucceed(connection, id);
        if (wasSuccessfullyApplied) {
            // Either the patch was executed before or the system was
            // bootstrapped
            // with the patch bean present.
            return null;
        }
        // it wasn't run and it can be run now
        executeScriptUrl(cfg, connection, scriptUrl);

    } catch (Throwable e) {
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Throwable e) {
            logger.warn("Error closing DB connection: " + e.getMessage());
        }
        // Remove the connection reference from the threadlocal boostrap
        // SchemaBootstrapConnectionProvider.setBootstrapConnection(null);
    }
    return null;
}

From source file:it.cnr.icar.eric.server.persistence.rdb.ConnectionPool.java

private Connection newConnection() throws SQLException {
    Connection conn = null;

    if ((user == null) || (user.length() == 0)) {
        conn = DriverManager.getConnection(URL);
    } else {//  w  w w  . j ava 2s.  c  om
        conn = DriverManager.getConnection(URL, user, password);
    }

    // Set Transaction Isolation and AutoComit
    // WARNING: till present Oracle dirvers (9.2.0.5) do not accept
    // setTransactionIsolation being called after setAutoCommit(false)
    conn.setTransactionIsolation(transactionIsolation);
    conn.setAutoCommit(false);

    return conn;
}

From source file:com.rosy.bill.dao.hibernate.SimpleHibernateDao.java

@SuppressWarnings("deprecation")
public String callProc(final String proc, final List<Object> paramList, final int outIndex, final int outType) {
    String result = null;/*from  w  w w . java2  s. c om*/
    java.sql.Connection conn = null;
    java.sql.CallableStatement cstmt = null;
    //Session session = this.getSession();
    try {

        conn = this.getSession().connection();
        conn.setAutoCommit(false);
        cstmt = conn.prepareCall(proc);
        for (int i = 0; paramList != null && i < paramList.size(); i++) {
            if (i + 1 == outIndex) {
                //cstmt.setInt(i + 1,
                //      (Integer.parseInt(paramList.get(i).toString())));
                cstmt.setString(i + 1, paramList.get(i).toString());
            } else {
                cstmt.setInt(i + 1, Integer.valueOf(paramList.get(i).toString()));
            }
        }
        cstmt.registerOutParameter(outIndex, outType);
        cstmt.execute();
        result = cstmt.getString(outIndex);
        conn.commit();
        //session.flush();
        //session.clear();
    } catch (Exception ex) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            logger.error("[" + proc + "]?" + e1.getMessage());
            e1.printStackTrace();
        }
        ex.printStackTrace();
    } finally {
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception ex) {
            }
        }
    }
    return result;
}

From source file:eionet.cr.dao.virtuoso.VirtuosoHarvestScriptDAO.java

/**
 * @see eionet.cr.dao.HarvestScriptDAO#move(eionet.cr.dto.HarvestScriptDTO.TargetType, java.lang.String, java.util.Set, int)
 *///  ww  w. jav  a  2 s.com
@Override
public void move(TargetType targetType, String targetUrl, Set<Integer> ids, int direction) throws DAOException {

    if (ids == null || ids.isEmpty()) {
        return;
    }

    if (direction == 0) {
        throw new IllegalArgumentException("Direction must not be 0!");
    }

    String sourceUrl = targetType != null && targetType.equals(TargetType.SOURCE) ? targetUrl : null;
    String typeUrl = targetType != null && targetType.equals(TargetType.TYPE) ? targetUrl : null;

    ArrayList<Object> values = new ArrayList<Object>();
    values.add(sourceUrl == null ? "" : sourceUrl);
    values.add(typeUrl == null ? "" : typeUrl);
    values.add(null);

    Connection conn = null;
    try {
        conn = getSQLConnection();
        conn.setAutoCommit(false);

        HarvestScriptDTOReader reader = new HarvestScriptDTOReader();
        SQLUtil.executeQuery(LIST_SQL, values, reader, conn);
        List<HarvestScriptDTO> scripts = reader.getResultList();

        // helper object for handling min, max positions and real count of scripts
        HarvestScriptSet scriptSet = new HarvestScriptSet(scripts);

        // If even one script is already at position 1 then moving up is not considered possible.
        // And conversely, if even one script is already at the last position, then moving down
        // is not considered possible either.
        boolean isMovingPossible = true;
        List<Integer> selectedPositions = new ArrayList<Integer>();
        for (HarvestScriptDTO script : scripts) {

            // we do this check only for scripts that have been selected
            if (ids.contains(script.getId())) {
                int position = script.getPosition();
                if ((direction < 0 && position == scriptSet.getMinPosition())
                        || (direction > 0 && position == scriptSet.getMaxPosition())) {
                    isMovingPossible = false;
                } else {
                    selectedPositions.add(position);
                }
            }
        }

        if (isMovingPossible) {

            if (direction < 0) {
                for (Integer selectedPosition : selectedPositions) {
                    HarvestScriptDTO scriptToMove = scriptSet.getScriptByPosition(selectedPosition);
                    int i = scripts.indexOf(scriptToMove);

                    scripts.set(i, scripts.get(i - 1));
                    scripts.set(i - 1, scriptToMove);
                }
            } else {
                for (int j = selectedPositions.size() - 1; j >= 0; j--) {
                    HarvestScriptDTO scriptToMove = scriptSet.getScriptByPosition(selectedPositions.get(j));
                    int i = scripts.indexOf(scriptToMove);

                    scripts.set(i, scripts.get(i + 1));
                    scripts.set(i + 1, scriptToMove);
                }
            }
        }

        values = new ArrayList<Object>();
        values.add(sourceUrl == null ? "" : sourceUrl);
        values.add(typeUrl == null ? "" : typeUrl);
        values.add(0, Integer.valueOf(scriptSet.getMaxPosition()));
        SQLUtil.executeUpdate(INCREASE_POSITIONS_SQL, values, conn);

        for (int i = 0; i < scripts.size(); i++) {

            values = new ArrayList<Object>();
            values.add(i + 1);
            values.add(Integer.valueOf(scripts.get(i).getId()));
            SQLUtil.executeUpdate(UPDATE_POSITION_SQL, values, conn);
        }

        conn.commit();
    } catch (Exception e) {
        SQLUtil.rollback(conn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(conn);
    }
}

From source file:com.glaf.core.jdbc.connection.DruidConnectionProvider.java

public Connection getConnection() throws SQLException {
    Connection connection = null;
    int count = 0;
    while (count < conf.getInt("jdbc.connection.retryCount", 10)) {
        try {/*ww w.  jav a2s. com*/
            connection = ds.getConnection();
            if (connection != null) {
                if (isolation != null) {
                    connection.setTransactionIsolation(isolation.intValue());
                }
                if (connection.getAutoCommit() != autocommit) {
                    connection.setAutoCommit(autocommit);
                }
                log.debug("druid connection: " + connection.toString());
                return connection;
            } else {
                count++;
                try {
                    Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException ex) {
            count++;
            try {
                Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count >= conf.getInt("jdbc.connection.retryCount", 10)) {
                ex.printStackTrace();
                throw ex;
            }
        }
    }
    return connection;
}

From source file:de.sqlcoach.db.jdbc.DBConnection.java

/**
 * Gets the simple connection.//from   w  ww.j av  a  2 s  .co m
 * 
 * @return the simple connection
 */
public static Connection getSimpleConnection(String dataSourceName) {

    log.info("getSimpleConnection ENTER ");
    String driver = "com.sap.dbtech.jdbc.DriverSapDB";
    String url = "jdbc:sapdb://localhost/SQLCOACH";
    String user = "SQLCOACH_DBA";
    String password = "sqlcoach";

    Connection cn = null;
    // final Properties props = new Properties();
    // try {
    // props.load(new FileInputStream(PROPERTIES_FILE));
    // } catch (FileNotFoundException e) {
    // log.error("getSimpleConnection : FileNotFoundException: \n" + e);
    // } catch (IOException e) {
    // log.error("getSimpleConnection : IOException: \n" + e);
    // }

    try {
        Class.forName("com.sap.dbtech.jdbc.DriverSapDB").newInstance();
    } catch (InstantiationException e1) {
        log.error("getSimpleConnection : Class.forName InstantiationException:\n" + e1);
    } catch (IllegalAccessException e1) {
        log.error("getSimpleConnection : Class.forName IllegalAccessException:\n" + e1);
    } catch (ClassNotFoundException e1) {
        log.error("getSimpleConnection : Class.forName ClassNotFoundException:\n" + e1);
    }

    /**
     * driver=com.sap.dbtech.jdbc.DriverSapDB
     * url=jdbc:sapdb://localhost/sqlcoach user=SQLCOACH_DBA password=test
     */

    // final String usr = props.getProperty("user");
    // final String pwd = props.getProperty("password");
    // final String url = props.getProperty("url");

    try {
        cn = DriverManager.getConnection(url, user, password);
        // cn = DriverManager.getConnection("jdbc: sapdb: // localhost/SQLCOACH");
        cn.setAutoCommit(false);
    } catch (Exception e) {
        log.error("getSimpleConnection : problems while establishing the connection:\n", e);
    }
    //      int connectionCnt = connectionCounter.get(dataSourceName);
    //      connectionCounter.put(dataSourceName, connectionCnt++);
    return cn;
}

From source file:com.gmt2001.datastore.SqliteStore.java

private static Connection CreateConnection(String dbname, int cache_size, boolean safe_write, boolean journal,
        boolean autocommit) {
    Connection connection = null;

    try {// w  w  w.ja  v  a 2s  .  co m
        SQLiteConfig config = new SQLiteConfig();
        config.setCacheSize(cache_size);
        config.setSynchronous(
                safe_write ? SQLiteConfig.SynchronousMode.FULL : SQLiteConfig.SynchronousMode.NORMAL);
        config.setTempStore(SQLiteConfig.TempStore.MEMORY);
        config.setJournalMode(journal ? SQLiteConfig.JournalMode.WAL : SQLiteConfig.JournalMode.OFF);
        connection = DriverManager.getConnection("jdbc:sqlite:" + dbname.replaceAll("\\\\", "/"),
                config.toProperties());
        connection.setAutoCommit(autocommit);
    } catch (SQLException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    return connection;
}