Example usage for java.sql Connection commit

List of usage examples for java.sql Connection commit

Introduction

In this page you can find the example usage for java.sql Connection commit.

Prototype

void commit() throws SQLException;

Source Link

Document

Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.

Usage

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

private void dropTimestampTables() throws SQLException {
    SqoopOptions options = new SqoopOptions(AUTH_CONNECT_STRING, null);
    options.setUsername(AUTH_TEST_USER);
    options.setPassword(AUTH_TEST_PASS);

    manager = new DirectMySQLManager(options);

    Connection connection = null;
    Statement st = null;//ww  w. j a v a  2  s .com

    connection = manager.getConnection();
    connection.setAutoCommit(false);
    st = connection.createStatement();

    try {
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable0");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable1");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable2");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable3");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable4");
        st.executeUpdate("DROP TABLE IF EXISTS mysqlTimestampTable5");
        connection.commit();
    } finally {
        st.close();
        connection.close();
    }
}

From source file:br.com.localizae.model.service.FileServiceLocal.java

@Override
public void upload(File file) throws Exception {
    Connection conn = null;

    try {/*from   ww w  . ja  v  a 2 s  .c  o m*/
        conn = ConnectionManager.getInstance().getConnection();
        FileDAO dao = new FileDAO();

        dao.create(conn, file);

        if (!file.getBase64().isEmpty()) {
            byte[] data = Base64.getDecoder().decode(file.getBase64());
            try (OutputStream stream = new FileOutputStream(Constantes.PATH_FILE + file.getUri())) {
                stream.write(data);
            }
        } else if (file.getFile().length != 0) {
            FileOutputStream fos = new FileOutputStream(Constantes.PATH_FILE + file.getUri());
            fos.write(file.getFile());

            fos.close();
        } else {
            throw new IllegalArgumentException(
                    " necessrio o envio do arquivo como array de byte ou como base64.");
        }

        conn.commit();
    } catch (Exception e) {
        conn.rollback();

        throw e;
    } finally {
        conn.close();
    }
}

From source file:org.apache.servicemix.nmr.audit.jdbc.JdbcAuditor.java

public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null) {
        throw new IllegalArgumentException("dataSource should not be null");
    }//from  www .j av  a  2  s  .c  o  m
    if (statements == null) {
        statements = new Statements();
        statements.setStoreTableName(tableName);
    }
    Connection connection = null;
    boolean restoreAutoCommit = false;
    try {
        connection = getDataSource().getConnection();
        if (connection.getAutoCommit()) {
            connection.setAutoCommit(false);
            restoreAutoCommit = true;
        }
        adapter = JDBCAdapterFactory.getAdapter(connection);
        if (statements == null) {
            statements = new Statements();
            statements.setStoreTableName(tableName);
        }
        adapter.setStatements(statements);
        if (createDataBase) {
            adapter.doCreateTables(connection);
        }
        connection.commit();
    } catch (SQLException e) {
        throw (IOException) new IOException("Exception while creating database").initCause(e);
    } finally {
        close(connection, restoreAutoCommit);
    }
    this.tccl = Thread.currentThread().getContextClassLoader();
}

From source file:com.cloudera.sqoop.TestIncrementalImport.java

/**
 * Create a table with an 'id' column full of integers and a
 * last_modified column with timestamps.
 *//*from w  w  w .  j ava2  s .  c o  m*/
private void createTimestampTable(String tableName, int insertRows, Timestamp baseTime) throws SQLException {
    SqoopOptions options = new SqoopOptions();
    options.setConnectString(SOURCE_DB_URL);
    HsqldbManager manager = new HsqldbManager(options);
    Connection c = manager.getConnection();
    PreparedStatement s = null;
    try {
        s = c.prepareStatement("CREATE TABLE " + tableName + "(id INT NOT NULL, " + "last_modified TIMESTAMP)");
        s.executeUpdate();
        c.commit();
        insertIdTimestampRows(tableName, 0, insertRows, baseTime);
    } finally {
        s.close();
    }
}

From source file:com.thinkmore.framework.orm.hibernate.SimpleHibernateDao.java

/**
 * ?/*from w ww.j ava 2 s .com*/
 * @param list sql?
 */
public void executeBatch(final List<String> list) {
    Connection conn = null;
    Statement st = null;
    try {
        conn = SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
        conn.setAutoCommit(false); // ??
        st = conn.createStatement();
        for (int i = 1, j = list.size(); i < j; i++) {
            String sql = list.get(i);
            st.addBatch(sql);
            if (i % 240 == 0) {//?240?sql???
                st.executeBatch();
                conn.commit();
                st.clearBatch();
            } else if (i % j == 0) {//??
                st.executeBatch();
                conn.commit();
                st.clearBatch();
            }
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        closeAll(st, conn);
    }
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Get the size of the buffer for a locale
 *
 * @param locale the locale to get the size
 *
 * @return The size of the buffer/*from  ww  w.j  av  a 2 s.  c o  m*/
 */
public int size(Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    int size = 0;

    try {
        con = datasource.getConnection();
        ps = con.prepareStatement("select count(*) from " + table + " where " + localeColumn + "=?");
        ps.setString(1, locale.toString());
        rs = ps.executeQuery();
        if (rs.next()) {
            size = rs.getInt(1);
        }
        rs.close();
        con.commit();
    } catch (SQLException e) {
        log.error(DB_ERROR, e);
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
        }
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
            }
        }
    }

    return size;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProjectSqlAdapter.java

public Project deleteProject(int projectID) throws AdaptationException {
    Project project = null;//from  w ww .  j  a  va2  s .  c  o m
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "SELECT * FROM Projects WHERE id = " + projectID;

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to delete project failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        project = getProject(resultSet);
        query = "DELETE FROM Projects WHERE id = " + projectID;

        statement.executeUpdate(query);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in deleteProject";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return project;
}

From source file:com.sf.springsecurityregistration1.core.repository.UserRepositoryJPA.java

private <T> void persistWithJDBC(T dto) throws SQLException {
    String table = dto.getClass().getAnnotation(javax.persistence.Table.class).name();
    //        System.out.println("table " + table);
    final String ROLE = "role";
    boolean isRole = table.toLowerCase().contains(ROLE);
    final String INSERT_USER = "INSERT INTO " + table + " (username, " + (isRole ? ROLE : "password")
            + ") VALUES (?, ?)";
    Connection connection = null;
    try {/*from w  w  w.java 2s .c om*/
        Properties connectionProps = new Properties();
        connectionProps.put("user", dbUsername);
        connectionProps.put("password", dbPassword);
        connection = DriverManager.getConnection(dbURL, connectionProps);
        connection.setAutoCommit(false);
        PreparedStatement insertUser = connection.prepareStatement(INSERT_USER);
        if (isRole) {
            UserRoles role = (UserRoles) dto;
            insertUser.setString(1, role.getUsername());
            insertUser.setString(2, role.getRole());
        } else {
            Users user = (Users) dto;
            insertUser.setString(1, user.getUsername());
            insertUser.setString(2, user.getPassword());
        }
        insertUser.execute();
        connection.commit();
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

public static void deleteChannelStatistics(String channelId) throws SQLException {
    long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId);
    Connection connection = null;
    PreparedStatement statement = null;

    try {/* www.ja  v a  2s .c o  m*/
        connection = getConnection();
        statement = connection.prepareStatement("DELETE FROM d_ms" + localChannelId);
        statement.executeUpdate();
        connection.commit();
    } finally {
        close(statement);
        close(connection);
    }

    ChannelController.getInstance().getStatistics().remove(channelId);
}

From source file:com.concursive.connect.web.modules.badges.dao.BadgeLogoFile.java

public boolean insert(Connection db) throws SQLException {
    boolean result = false;
    // The required linkModuleId
    linkModuleId = Constants.BADGE_FILES;
    // Determine if the database is in auto-commit mode
    boolean doCommit = false;
    try {/*  w  w  w .  ja v  a  2 s  .  c o m*/
        if (doCommit = db.getAutoCommit()) {
            db.setAutoCommit(false);
        }
        // Insert the record
        result = super.insert(db);
        // Update the referenced pointer
        if (result) {
            int i = 0;
            PreparedStatement pst = db
                    .prepareStatement("UPDATE badge " + "SET logo_id = ? " + "WHERE badge_id = ? ");
            pst.setInt(++i, id);
            pst.setInt(++i, linkItemId);
            int count = pst.executeUpdate();
            result = (count == 1);
        }
        if (doCommit) {
            db.commit();
        }
    } catch (Exception e) {
        if (doCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (doCommit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}