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.agiletec.aps.system.services.pagemodel.PageModelDAO.java

@Override
public void deleteModel(String code) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {//from  ww w.  j  a v  a2  s. co m
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(DELETE_PAGEMODEL);
        stat.setString(1, code);
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error while deleting a model", t);
        throw new RuntimeException("Error while deleting a model", t);
    } finally {
        this.closeDaoResources(null, stat, conn);
    }
}

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

/**
 * Update an item to operationalize it.//from  w  ww  .  j  av a 2  s  . c  o  m
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param itemId the item id.
 * @return the created test case id.
 * @since July, 2011.
 * @throws ItemUpdateDAOException if an error occurs during the update.
 */
@Override
public int operationalizeItem(int itemId) throws ItemUpdateDAOException {
    LOGGER.debug("operationalizeItem(" + itemId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO test_case(test_case_id) VALUES(nextval('test_case_id_seq')) ");
        Integer createdTestCase = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(test_case_id)::int AS testCaseId FROM test_case ", new ScalarHandler("testCaseId"));
        getQueryRunner().update(connection, "UPDATE item SET test_case_id = ? WHERE item_id = ? ",
                new Object[] { createdTestCase, itemId });
        connection.commit();
        return createdTestCase;
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ItemUpdateDAOException(e);
        }
        throw new ItemUpdateDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

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

/**
 * Update an item to refine it.//from w  w  w.ja  v  a2s  . c om
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param itemId the item id.
 * @return the created action plan id.
 * @since July, 2011.
 * @throws ItemUpdateDAOException if an error occurs during the update.
 */
@Override
public int refineItem(int itemId) throws ItemUpdateDAOException {
    LOGGER.debug("refineItem(" + itemId + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO action_plan(action_plan_id) VALUES(nextval('action_plan_seq')) ");
        Integer createdActionPlan = (Integer) getQueryRunner().query(connection,
                "SELECT MAX(action_plan_id)::int AS actionPlanId FROM action_plan ",
                new ScalarHandler("actionPlanId"));
        getQueryRunner().update(connection, "UPDATE item SET action_plan_id = ? WHERE item_id = ? ",
                new Object[] { createdActionPlan, itemId });
        connection.commit();
        return createdActionPlan;
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ItemUpdateDAOException(e1);
        }
        throw new ItemUpdateDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:net.fender.sql.DriverConnectionFactory.java

public Connection getConnection() throws SQLException {
    // don't log properties as it contains plain text user name and password
    log.debug("creating connection to " + driver + " " + url);
    Connection connection = driver.connect(url, properties);
    if (autoCommit != null) {
        connection.setAutoCommit(autoCommit);
    }/* www .  ja  v a 2  s.  c  o  m*/
    if (holdability != null) {
        connection.setHoldability(holdability.getHoldability());
    }
    if (readOnly != null) {
        connection.setReadOnly(readOnly);
    }
    if (transactionIsolation != null) {
        connection.setTransactionIsolation(transactionIsolation.getLevel());
    }
    if (catalog != null) {
        connection.setCatalog(catalog);
    }
    return connection;
}

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

/**
 * Creates the documentation of an activity from actions and parameters
 * lists.//from w w  w  .j a va  2 s.  c o  m
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param activity the activity to document.
 * @param actions the actions list.
 * @param parameters the parameters list.
 * @since July, 2011.
 * @throws ActivityDocumentationCreationDAOException if an error occurs
 *         during the creation.
 */
@Override
public void createActivityDocumentation(Activity activity, List<ActivityAction> actions,
        List<ActivityParameter> parameters) throws ActivityDocumentationCreationDAOException {
    LOGGER.debug("createActivityDocumentation(" + activity.getActivityId() + "," + actions.size() + " actions,"
            + parameters.size() + " parameters).");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection, "UPDATE activity SET global_description = ? WHERE activity_id = ? ",
                new Object[] { activity.getGlobalDescription(), activity.getActivityId() });
        int cpt = 1;
        for (ActivityAction action : actions) {
            getQueryRunner().update(connection,
                    "INSERT INTO activity_action(activity_action_id, activity_id, description, result, \"order\") VALUES(nextval('activity_action_id_seq'),?,?,?,?) ",
                    new Object[] { activity.getActivityId(), action.getDescription(), action.getResult(),
                            cpt++ });
        }
        for (ActivityParameter parameter : parameters) {
            getQueryRunner().update(connection,
                    "INSERT INTO activity_parameter(activity_parameter_id, activity_id, name, description) VALUES(nextval('activity_parameter_id_seq'),?,?,?) ",
                    new Object[] { activity.getActivityId(), "{" + parameter.getName() + "}",
                            parameter.getDescription() });
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new ActivityDocumentationCreationDAOException(e1);
        }
        throw new ActivityDocumentationCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.agiletec.aps.system.services.pagemodel.PageModelDAO.java

@Override
public void addModel(PageModel model) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {//  w w w . j  av a  2s  .com
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(ADD_PAGEMODEL);
        stat.setString(1, model.getCode());
        stat.setString(2, model.getDescription());
        PageModelDOM dom = new PageModelDOM(model);
        stat.setString(3, dom.getXMLDocument());
        String pluginCode = (StringUtils.isBlank(model.getPluginCode())) ? null : model.getPluginCode();
        stat.setString(4, pluginCode);
        String template = (StringUtils.isBlank(model.getTemplate())) ? null : model.getTemplate();
        stat.setString(5, template);
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error while adding a model", t);
        throw new RuntimeException("Error while adding a model", t);
    } finally {
        this.closeDaoResources(null, stat, conn);
    }
}

From source file:com.agiletec.aps.system.services.pagemodel.PageModelDAO.java

@Override
public void updateModel(PageModel model) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {/*  w ww. j a  v a  2  s  .co m*/
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(UPDATE_PAGEMODEL);
        stat.setString(1, model.getDescription());
        PageModelDOM dom = new PageModelDOM(model);
        stat.setString(2, dom.getXMLDocument());
        String pluginCode = (StringUtils.isBlank(model.getPluginCode())) ? null : model.getPluginCode();
        stat.setString(3, pluginCode);
        String template = (StringUtils.isBlank(model.getTemplate())) ? null : model.getTemplate();
        stat.setString(4, template);
        stat.setString(5, model.getCode());
        stat.executeUpdate();
        conn.commit();
    } catch (Throwable t) {
        this.executeRollback(conn);
        _logger.error("Error while updating a model", t);
        throw new RuntimeException("Error while updating a model", t);
    } finally {
        this.closeDaoResources(null, stat, conn);
    }
}

From source file:com.cloudera.sqoop.testutil.HsqldbTestServer.java

public Connection getConnection() throws SQLException {
    try {/*  ww w  .j a v  a  2  s  . c  om*/
        Class.forName(DRIVER_CLASS);
    } catch (ClassNotFoundException cnfe) {
        LOG.error("Could not get connection; driver class not found: " + DRIVER_CLASS);
        return null;
    }

    Connection connection = DriverManager.getConnection(DB_URL);
    connection.setAutoCommit(false);
    return connection;
}

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

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;/*  w  w w  .  j a  v a2  s.c  om*/
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "UPDATE user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ? "
                + "WHERE userid = ?";
        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.setLong(8, webSocket.getCharacter().getUserId());
        ps.executeUpdate();
        ps.close();

        sql = "UPDATE setting SET privategrade = ?, privatesex = ?, privatebirth =? WHERE userid = ?";
        ps = con.prepareStatement(sql);
        ps.setInt(1, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(2, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vbirthday").toString()));
        ps.setLong(4, webSocket.getCharacter().getUserId());

        ps.executeUpdate();
        ps.close();

        con.commit();

        //TODO 
        responseJSON.put("status", 0);
    } 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:consultor.CSVLoader.java

/**
 * Parse CSV file using OpenCSV library and load in 
 * given database table. //from  www . j a va 2s .com
 * @param csvFile Input CSV file
 * @param tableName Database table name to import data
 * @param truncateBeforeLoad Truncate the table before inserting 
 *          new records.
 * @throws Exception
 */
public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad) throws Exception {

    CSVReader csvReader = null;
    if (null == this.connection) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = new CSVReader(new FileReader(csvFile), this.seprator);

    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    System.out.println("Query: " + query);

    String[] nextLine;
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = this.connection;
        con.setAutoCommit(false);
        ps = con.prepareStatement(query);

        if (truncateBeforeLoad) {
            //delete data from table before loading csv
            con.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        Date date = null;
        while ((nextLine = csvReader.readNext()) != null) {

            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    date = DateUtil.convertToDate(string);
                    if (null != date) {
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                    } else {
                        ps.setString(index++, string);
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        con.commit();
    } catch (Exception e) {
        con.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps)
            ps.close();
        if (null != con)
            con.close();

        csvReader.close();
    }
}