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.stratelia.webactiv.util.DBUtilTest.java

/**
 * Test of getMaxFromTable method, of class DBUtil.
 *//* w  ww.  j a va  2 s.c  om*/
@Test
public void testGetMaxFromTable() throws Exception {

    Connection connection = dataSource.getConnection();
    try {
        connection.setAutoCommit(false);
        String tableName = "sb_test_dbutil_connection";
        String idName = "id";
        int result = DBUtil.getMaxFromTable(connection, tableName, idName);
        assertThat(result, is(1));
    } finally {
        connection.close();
    }
}

From source file:datawarehouse.CSVLoader.java

/**
 * Parse CSV file using OpenCSV library and load in given database table.
 *
 * @param csvFile Input CSV file/*from w  ww .ja  v  a 2 s  .co  m*/
 * @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;
        while ((nextLine = csvReader.readNext()) != null) {
            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    //System.out.print(string + ": ");
                    try {
                        DateFormat format = new SimpleDateFormat("dd.mm.yyyy");
                        Date date = format.parse(string);
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                        //System.out.println("date");
                    } catch (ParseException | SQLException e) {
                        try {
                            Double income = parseDouble(string.replace(",", "."));
                            ps.setDouble(index++, income);
                            //System.out.println("double");
                        } catch (NumberFormatException | SQLException err) {
                            ps.setString(index++, string);
                            //System.out.println("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();
    }
}

From source file:io.undertow.server.handlers.JDBCLogDatabaseTestCase.java

@After
public void teardown() throws SQLException {

    Connection conn = null;
    Statement statement = null;/*w  w  w  . j ava2  s.c  o m*/
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(true);
        statement = conn.createStatement();
        statement.executeUpdate("DROP TABLE PUBLIC.ACCESS;");
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (conn != null) {
            conn.close();
        }

    }
    ds.dispose();
    ds = null;
}

From source file:io.undertow.server.handlers.JDBCLogDatabaseTestCase.java

@Before
public void setup() throws SQLException {
    ds = JdbcConnectionPool.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "user", "password");
    Connection conn = null;
    Statement statement = null;/*from   w  w w.ja va 2  s  .com*/
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(true);
        statement = conn.createStatement();
        statement.executeUpdate("CREATE TABLE PUBLIC.ACCESS (" + " id SERIAL NOT NULL,"
                + " remoteHost CHAR(15) NOT NULL," + " userName CHAR(15)," + " timestamp TIMESTAMP NOT NULL,"
                + " virtualHost VARCHAR(64)," + " method VARCHAR(8)," + " query VARCHAR(255) NOT NULL,"
                + " status SMALLINT UNSIGNED NOT NULL," + " bytes INT UNSIGNED NOT NULL,"
                + " referer VARCHAR(128)," + " userAgent VARCHAR(128)," + " PRIMARY KEY (id)" + " );");
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (conn != null) {
            conn.close();
        }

    }

}

From source file:com.fileanalyzer.dao.impl.FileStatisticDAOImpl.java

@Override
public void add(FileStatistic fStat) {
    Connection con = null;
    PreparedStatement preparedStatement = null;
    try {//w  w  w  .j  a  v a  2  s.c o  m
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        preparedStatement = con.prepareStatement(getInsertByFileStatistic(fStat));
        preparedStatement.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, preparedStatement);
    }
}

From source file:com.fileanalyzer.dao.impl.FileStatisticDAOImpl.java

@Override
public void update(FileStatistic fStat) {
    Connection con = null;
    PreparedStatement preparedStatement = null;
    try {/*from   w w w. java 2s .co m*/
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        preparedStatement = con.prepareStatement(SqlGenerator.getUpdateByFileStatistic(fStat));
        preparedStatement.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        handleException(e, con);
    } finally {
        doFinal(con, preparedStatement);
    }
}

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

/**
 * Creates an user from his properties bean.
 * //from  w w w. j a  va2  s .  c o m
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @param userToCreateBean the properties to use to create the user.
 * @throws UserCreationDAOException if an error occurs during the creation.
 */
@Override
public void createUserFromBean(UserCreation userToCreateBean) throws UserCreationDAOException {
    LOGGER.debug("createUserFromBean(" + userToCreateBean.getLogin() + ").");
    Connection connection = null;
    try {
        connection = getDataSource().getConnection();
        connection.setAutoCommit(false);
        getQueryRunner().update(connection,
                "INSERT INTO \"user\"(user_id, \"login\", \"password\", \"name\", last_name, creation_date, job) VALUES(nextval('user_seq'), ?, md5(?), ?, ?, NOW(), ?) ",
                new Object[] { userToCreateBean.getLogin(), userToCreateBean.getPassword(),
                        userToCreateBean.getName().toUpperCase(), userToCreateBean.getLastName(),
                        userToCreateBean.getJob() });
        Integer createdUserID = (Integer) getQueryRunner().query(connection,
                "SELECT user_id::int FROM \"user\" WHERE \"login\" = ? ", new ScalarHandler("user_id"),
                new Object[] { userToCreateBean.getLogin() });
        getQueryRunner().update(connection, "INSERT INTO user_role(user_id, role) VALUES(?, 'ROLE_USER') ",
                new Object[] { createdUserID });
        if (userToCreateBean.isAdministrator()) {
            getQueryRunner().update(connection, "INSERT INTO user_role(user_id, role) VALUES(?, 'ROLE_ADMIN') ",
                    new Object[] { createdUserID });
        }
        if (userToCreateBean.isResponsable()) {
            getQueryRunner().update(connection, "INSERT INTO user_role(user_id, role) VALUES(?, 'ROLE_RESP') ",
                    new Object[] { createdUserID });
        }
        getQueryRunner().update(connection,
                "INSERT INTO user_service(user_id, service_id, hired_date) VALUES(?, ?, NOW()) ",
                new Object[] { createdUserID, userToCreateBean.getServiceId() });
        connection.commit();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            throw new UserCreationDAOException(e1);
        }
        throw new UserCreationDAOException(e);
    } finally {
        if (null != connection) {
            DbUtils.closeQuietly(connection);
        }
    }
}

From source file:com.reydentx.core.client.MySQLClient.java

private Connection _borrowClient() throws Exception {
    Connection client = null;
    try {//ww w .  ja  v  a2s.c o m
        client = (Connection) _pool.borrowObject();
        client.setAutoCommit(true);
    } catch (Exception ex) {
        System.out.println(ex.toString());
        _logger.error("_borrowClient: error", ex);
        invalidClient(client);
        throw ex;
    }
    return client;
}

From source file:com.fileanalyzer.dao.impl.FileStatisticDAOImpl.java

@Override
public void delete(FileStatistic fStat) {
    Connection con = null;
    Statement statement = null;//  w  ww  .  j  ava2 s.  co m
    try {
        con = DBConnector.getConnection();
        con.setAutoCommit(false);
        statement = con.createStatement();
        statement.execute("delete from " + FileStatistic.FileStatisticKey.TABLE + " where id=" + fStat.getId());
        con.commit();
    } catch (SQLException e) {
        if (con != null) {
            try {
                log.error("Transaction is being rolled back", e);
                con.rollback();
            } catch (SQLException excep) {
                log.error(excep);
            }
        }
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                log.error(ex);
            }
        }
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            log.error("setAutoCommit(true)", ex);
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
                log.error(ex);
            }
        }
    }
}

From source file:com.mmnaseri.dragonfly.dialect.impl.Mysql5Dialect.java

@Override
public synchronized <E> Map<String, Object> loadTableValues(final TableMetadata<?> generatorMetadata,
        TableMetadata<E> tableMetadata, final DataAccessSession session) {
    final HashMap<String, Object> result = new HashMap<String, Object>();
    with(tableMetadata.getColumns()).forThose(new Filter<ColumnMetadata>() {
        @Override/* ww w . j  a v  a 2 s  .co  m*/
        public boolean accepts(ColumnMetadata item) {
            return ValueGenerationType.TABLE.equals(item.getGenerationType());
        }
    }, new Processor<ColumnMetadata>() {
        @Override
        public void process(ColumnMetadata column) {
            final String valueGenerator;
            if (column.getValueGenerator() == null || column.getValueGenerator().isEmpty()) {
                valueGenerator = column.getTable().getEntityType().getCanonicalName() + "."
                        + column.getPropertyName();
            } else {
                valueGenerator = column.getValueGenerator();
            }
            initializeGenerator(session, generatorMetadata, valueGenerator);
            final Connection connection = session.getConnection();
            try {
                connection.setAutoCommit(false);
                final Statement statement = connection.createStatement();
                final String escapedGenerator = DatabaseUtils.escapeString(valueGenerator,
                        session.getDatabaseDialect().getStringEscapeCharacter());
                final String table = DatabaseUtils.qualifyTable(generatorMetadata,
                        session.getDatabaseDialect());
                final String query = "SELECT `value` FROM " + table + " WHERE `name` = \"" + escapedGenerator
                        + "\" FOR UPDATE;";
                log.trace("Querying for key: " + query);
                final ResultSet resultSet = statement.executeQuery(query);
                resultSet.next();
                final Map<String, Object> map = rowHandler.handleRow(resultSet);
                resultSet.close();
                final String update = "UPDATE " + table + " SET `value` = `value` + 1 WHERE `name` = \""
                        + escapedGenerator + "\"";
                log.trace("Updating key: " + update);
                statement.executeUpdate(update);
                result.put(column.getName(), map.get("value"));
                connection.commit();
                connection.close();
            } catch (Exception e) {
                throw new UnsuccessfulOperationError("Failed to load generated key for " + column.getName(), e);
            }
        }
    });
    return result;
}