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.migratebird.database.impl.DefaultSQLHandler.java

private void reenableAutoCommit(Connection connection) {
    try {//  w w w .j av a2 s .c  om
        connection.setAutoCommit(true);

    } catch (Exception t) {
        logger.warn("Unable to re-enable auto commit behavior.");
    }
}

From source file:com.che.software.testato.domain.dao.jdbc.impl.MatrixResultDAO.java

/**
 * Creates the matrix results for a given iteration assignment. The related
 * matrix must be completed before calling this method.
 * // w  w  w.  j  a va  2  s. co m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param iterationId the given iteration id.
 * @since August, 2011.
 * @throws MatrixResultCreationDAOException if an error occurs during the
 *         creation.
 */
@Override
public void createMatrixResults(int iterationId) throws MatrixResultCreationDAOException {
    LOGGER.debug("createMatrixResults(" + iterationId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        for (MatrixResult result : getQueryRunner().query(connection,
                "SELECT first_script AS scriptId, iteration_assignment_id AS iterationAssignmentId, ((SUM((value/( SELECT SUM(value) FROM comparisonMatrixItem WHERE iteration_assignment_id = ? AND second_script = base.second_script GROUP BY second_script ORDER BY second_script ))))/COUNT(*))::numeric(15,2) AS percentage FROM comparisonMatrixItem base WHERE iteration_assignment_id = ? GROUP BY first_script,iteration_assignment_id ORDER BY first_script ",
                new BeanListHandler<MatrixResult>(MatrixResult.class),
                new Object[] { iterationId, iterationId })) {
            getQueryRunner().update(connection,
                    "INSERT INTO iteration_assignment_source_script(script_id, iteration_assignment_id, percentage) VALUES(?, ?, ?) ",
                    new Object[] { result.getScriptId(), result.getIterationAssignmentId(),
                            result.getPercentage() });
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new MatrixResultCreationDAOException(e1);
        }
        throw new MatrixResultCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.che.software.testato.domain.dao.jdbc.impl.HierarchyDAO.java

/**
 * Creates a hierarchy from a bean of criterions.
 * //from  w ww . ja va  2 s. c  o  m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param creationBean the bean of criterions.
 * @since July, 2011.
 * @throws HierarchyCreationDAOException if an error occurs during the
 *         creation.
 */
@Override
public void createHierarchyFromBean(HierarchyCreation creationBean) throws HierarchyCreationDAOException {
    LOGGER.debug("createHierarchyFromBean().");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO hirearchy(hierarchy_id, creation_date, last_update_date, user_id, high_level_goal) VALUES(nextval('hierarchy_seq'), NOW(), NOW(), ?, ?) ",
                new Object[] { creationBean.getUser().getUserId(), creationBean.getHighLevelGoal() });
        Integer createdHierarchyId = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(hierarchy_id)::int AS hierarchy_id FROM hirearchy ",
                new ScalarHandler("hierarchy_id"));
        getQueryRunner().update(connection,
                "INSERT INTO hierarchy_version(version_id, hierarchy_id) VALUES(?, ?) ",
                new Object[] { creationBean.getVersion().getVersionId(), createdHierarchyId });
        getQueryRunner().update(connection,
                "INSERT INTO action_plan(action_plan_id) VALUES(nextval('action_plan_seq')) ");
        Integer createdActionPlanId = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(action_plan_id)::int AS action_plan_id FROM action_plan ",
                new ScalarHandler("action_plan_id"));
        getQueryRunner().update(connection,
                "INSERT INTO hierarchy_action_plan(hierarchy_id, action_plan_id) VALUES(?, ?) ",
                new Object[] { createdHierarchyId, createdActionPlanId });
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new HierarchyCreationDAOException(e1);
        }
        throw new HierarchyCreationDAOException(e);
    } finally {
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new HierarchyCreationDAOException(e);
            }
        }
    }
}

From source file:jp.co.tis.gsp.tools.dba.mojo.LoadDataMojo.java

@Override
protected void executeMojoSpec() throws MojoExecutionException, MojoFailureException {
    List<File> files = CollectionsUtil
            .newArrayList(FileUtils.listFiles(dataDirectory, new String[] { "csv" }, true));
    DriverManagerUtil.registerDriver(driver);
    Connection conn = null;
    try {//from w  ww  .ja va  2 s.co  m
        conn = DriverManager.getConnection(url, user, password);
        conn.setAutoCommit(false);
    } catch (SQLException e) {
        getLog().error(
                "DB?????????driver??url?????????????");
        throw new MojoExecutionException("", e);
    }

    // ????
    EntityDependencyParser parser = new EntityDependencyParser();
    Dialect dialect = DialectFactory.getDialect(url);
    parser.parse(conn, url, dialect.normalizeSchemaName(schema));
    final List<String> tableList = parser.getTableList();
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(File f1, File f2) {
            return getIndex(FilenameUtils.getBaseName(f1.getName()))
                    - getIndex(FilenameUtils.getBaseName(f2.getName()));
        }

        private int getIndex(String tableName) {
            for (int i = 0; i < tableList.size(); i++) {
                if (StringUtil.equalsIgnoreCase(tableName, tableList.get(i))) {
                    return i;
                }
            }
            return 0;
        }

    });
    try {
        for (File file : files) {
            CsvReader reader = null;
            String fileName = file.getName();
            FileInputStream in = FileInputStreamUtil.create(file);
            try {
                getLog().info("????:" + fileName);
                if (specifiedEncodingFiles != null && specifiedEncodingFiles.containsKey(fileName)) {
                    String encoding = (String) specifiedEncodingFiles.get(fileName);
                    reader = new CsvReader(in, Charset.forName(encoding));
                    getLog().info(" -- encoding:" + encoding);
                } else {
                    reader = new CsvReader(in, SJIS);
                }
                String tableName = StringUtils.upperCase(FilenameUtils.getBaseName(fileName));
                reader.readHeaders();
                String[] headers = reader.getHeaders();
                CsvInsertHandler insertHandler = new CsvInsertHandler(conn, dialect,
                        dialect.normalizeSchemaName(schema), tableName, headers);
                insertHandler.prepare();

                while (reader.readRecord()) {
                    String[] values = reader.getValues();

                    for (int i = 0; i < values.length; i++) {
                        insertHandler.setObject(i + 1, values[i]);
                    }
                    insertHandler.execute();
                }

                insertHandler.close();
            } catch (IOException e) {
                getLog().warn("??????:" + file, e);
            } catch (SQLException e) {
                getLog().warn("SQL??????:" + file, e);
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
    } finally {
        ConnectionUtil.close(conn);
    }
}

From source file:com.oic.event.RegisterProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;//  ww  w  .ja v  a  2  s .  co  m
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "INSERT INTO user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ?, secretkey = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setString(8, json.get("secretkey").toString());
        ps.executeUpdate();
        ps.close();

        sql = "SELECT last_insert_id() AS last";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            throw new SQLException();
        }
        long userid = rs.getLong("last");
        rs.close();
        ps.close();

        sql = "INSERT INTO setting SET userid = ?, privategrade = ?, privatesex = ?, privatebirth = ?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, userid);
        ps.setInt(2, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(4, Integer.parseInt(json.get("vbirthday").toString()));
        ps.executeUpdate();
        ps.close();
        con.commit();

        responseJSON.put("status", 0);
        webSocket.userNoLogin();
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }
    webSocket.sendJson(responseJSON);
}

From source file:com.stratelia.webactiv.util.DBUtil.java

/**
 * Return a new unique Id for a table./*  w  w w .  ja v a  2  s.  c  o m*/
 * @param tableName the name of the table.
 * @param idName the name of the column.
 * @return a unique id.
 * @throws UtilException
 */
public static int getNextId(String tableName, String idName) throws UtilException {
    Connection privateConnection = null;
    boolean testingMode = false;
    try {
        // On ne peux pas utiliser une simple connection du pool
        // on utilise une connection extrieure au contexte transactionnel des ejb
        synchronized (DBUtil.class) {
            if (getInstance().connectionForTest != null) {
                privateConnection = getInstance().connectionForTest;
                testingMode = true;
            } else {
                privateConnection = ConnectionPool.getConnection();
            }
        }
        privateConnection.setAutoCommit(false);
        return getNextId(privateConnection, tableName, idName);
    } catch (Exception ex) {
        SilverTrace.debug("util", "DBUtil.getNextId", "impossible de recuprer le prochain id", ex);
        if (privateConnection != null) {
            rollback(privateConnection);
        }
        throw new UtilException("DBUtil.getNextId",
                new MultilangMessage("util.MSG_CANT_GET_A_NEW_UNIQUE_ID", tableName, idName).toString(), ex);
    } finally {
        try {
            if (privateConnection != null && !testingMode) {
                privateConnection.close();
            }
        } catch (SQLException e) {
            SilverTrace.error("util", "DBUtil.getNextId", "root.EX_CONNECTION_CLOSE_FAILED", e);
        }
    }
}

From source file:com.stratelia.webactiv.util.DBUtilTest.java

/**
 * Test of getNextId method, of class DBUtil.
 *///  ww  w  . jav  a2 s.co m
@Test
public void testGetNextIdWithConnectionInexistingLine() throws Exception {
    String tableName = "sb_simple_document";
    String idName = "id";
    Connection connection = dataSource.getConnection();
    try {
        connection.setAutoCommit(false);
        int result = DBUtil.getNextId(connection, tableName, idName);
        assertThat(result, is(1));
    } finally {
        connection.close();
    }
}

From source file:com.stratelia.webactiv.util.DBUtilTest.java

/**
 * Test of getNextId method, of class DBUtil.
 *///from  w w w  .j av  a2  s.com
@Test
public void testGetNextIdWithConnectionExistingLine() throws Exception {
    String tableName = "sb_test_dbutil_connection";
    String idName = "id";
    Connection connection = dataSource.getConnection();
    try {
        connection.setAutoCommit(false);
        int result = DBUtil.getNextId(connection, tableName, idName);
        assertThat(result, is(501));
    } finally {
        connection.close();
    }
}

From source file:com.stratelia.webactiv.util.DBUtilTest.java

/**
 * Test of getMaxId method, of class DBUtil.
 *//* w  w  w .  ja v a 2  s. c  o  m*/
@Test
public void testGetMaxIdWithExistingLine() throws Exception {
    Connection connection = dataSource.getConnection();
    try {
        connection.setAutoCommit(false);
        String tableName = "sb_test_dbutil_connection";
        String idName = "id";
        int result = DBUtil.getMaxId(connection, tableName, idName);
        assertThat(result, is(501));
    } finally {
        connection.close();
    }
}

From source file:com.stratelia.webactiv.util.DBUtilTest.java

/**
 * Test of getMaxId method, of class DBUtil.
 *//*from w w  w. j  a va 2  s  .  c  om*/
@Test
public void testGetMaxIdWithInexistingLine() throws Exception {
    Connection connection = dataSource.getConnection();
    try {
        connection.setAutoCommit(false);
        String tableName = "sb_simple_document";
        String idName = "id";
        int result = DBUtil.getMaxId(connection, tableName, idName);
        assertThat(result, is(1));
    } finally {
        connection.close();
    }
}