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.netflix.metacat.usermetadata.mysql.MysqlUserMetadataService.java

protected int executeUpdateForKey(final String query, final String... keyValues) {
    int result = 0;
    try {/*  ww w  .  ja va 2s  . co  m*/
        final Connection conn = poolingDataSource.getConnection();
        try {
            result = new QueryRunner().update(conn, query, (Object[]) keyValues);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    } catch (SQLException e) {
        log.error("Sql exception", e);
        throw new UserMetadataServiceException(
                String.format("Failed to save data for %s", Arrays.toString(keyValues)), e);
    }
    return result;
}

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

/**
 * @see eionet.cr.dao.HarvestScriptDAO#delete(eionet.cr.dto.HarvestScriptDTO)
 *///from  ww  w.jav a  2s .c om
@Override
public void delete(List<Integer> ids) throws DAOException {

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

    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = getSQLConnection();
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(DELETE_SQL);
        for (Integer id : ids) {
            stmt.setInt(1, id);
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        SQLUtil.rollback(conn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(stmt);
        SQLUtil.close(conn);
    }
}

From source file:eionet.gdem.dcm.conf.DbTest.java

public void tstDbParams(String url, String user, String psw) throws Exception {

    Connection con = null;
    Statement stmt = null;/*w  ww .  j  a  v  a 2 s  .c o m*/
    ResultSet rset = null;

    try {
        // Class.forName(Properties.dbDriver);
        Class.forName(Properties.dbDriver);

        con = DriverManager.getConnection(url, user, psw);
        stmt = con.createStatement();
        String sql = "SELECT 1";
        rset = stmt.executeQuery(sql);

    } catch (Exception e) {
        LOGGER.debug("Testing database connection failed!", e);
        e.printStackTrace();
        throw new DCMException(BusinessConstants.EXCEPTION_PARAM_DB_TEST_FAILED);
    } finally {
        // Close connection
        if (rset != null) {
            rset.close();
        }
        if (stmt != null) {
            stmt.close();
            if (!con.getAutoCommit()) {
                con.commit();
            }
        }
        if (con != null) {
            con.close();
            con = null;
        }

    }
}

From source file:com.cloudera.sqoop.tool.EvalSqlTool.java

@Override
/** {@inheritDoc} */
public int run(SqoopOptions options) {
    if (!init(options)) {
        return 1;
    }/*from   ww  w. ja  va  2  s.c o  m*/

    PreparedStatement stmt = null;
    ResultSet rs = null;
    PrintWriter pw = null;
    try {
        Connection c = manager.getConnection();
        String query = options.getSqlQuery();
        LOG.debug("SQL query: " + query);
        stmt = c.prepareStatement(query);
        boolean resultType = stmt.execute();
        // Iterate over all the results from this statement.
        while (true) {
            LOG.debug("resultType=" + resultType);
            if (!resultType) {
                // This result was an update count.
                int updateCount = stmt.getUpdateCount();
                LOG.debug("updateCount=" + updateCount);
                if (updateCount == -1) {
                    // We are done iterating over results from this statement.
                    c.commit();
                    break;
                } else {
                    LOG.info(updateCount + " row(s) updated.");
                }
            } else {
                // This yields a ResultSet.
                rs = stmt.getResultSet();
                pw = new PrintWriter(System.out, true);
                new ResultSetPrinter().printResultSet(pw, rs);
                pw.close();
                pw = null;
            }

            resultType = stmt.getMoreResults();
        }
    } catch (IOException ioe) {
        LOG.warn("IOException formatting results: " + StringUtils.stringifyException(ioe));
        return 1;
    } catch (SQLException sqlE) {
        LOG.warn("SQL exception executing statement: " + StringUtils.stringifyException(sqlE));
        return 1;
    } finally {
        if (null != pw) {
            pw.close();
        }
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException sqlE) {
                LOG.warn("SQL exception closing ResultSet: " + StringUtils.stringifyException(sqlE));
            }
        }
        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException sqlE) {
                LOG.warn("SQL exception closing statement: " + StringUtils.stringifyException(sqlE));
            }
        }
        destroy(options);
    }

    return 0;
}

From source file:com.concursive.connect.web.portal.PortletPreferencesServiceImpl.java

public void store(PortletWindow portletWindow, PortletRequest request, InternalPortletPreference[] preferences)
        throws PortletContainerException {
    String key = getFormattedKey(portletWindow);
    if (key.startsWith("T")) {
        LOG.debug("Storing temporary portlet prefs");
        DashboardPortlet portlet = (DashboardPortlet) request.getAttribute("dashboardPortlet");
        LOG.debug("write------------------------------------");
        LOG.debug("portlet page name: " + portlet.getPageName());
        LOG.debug("portlet key: " + portlet.getWindowConfigId());
        LOG.debug("portlet formatted key: " + key);
        LOG.debug("-----------------------------------------");
        // Store them in an array for quick retrieval
        storage.put(key, clonePreferences(preferences));
    } else {//w  w w  .j a v a 2s  .co m
        // Store them in an array for quick retrieval
        storage.put(key, clonePreferences(preferences));
        // Store the preferences into the database -- container does not specify what changed
        // so delete them all
        int portletId = Integer.parseInt(key);
        Connection db = (Connection) request.getAttribute("connection");
        try {
            db.setAutoCommit(false);
            DashboardPortletPrefsList.delete(db, portletId);
            for (InternalPortletPreference thisPref : preferences) {
                DashboardPortletPrefs portletPrefs = new DashboardPortletPrefs();
                portletPrefs.setPortletId(portletId);
                portletPrefs.setName(thisPref.getName());
                portletPrefs.setValues(thisPref.getValues());
                portletPrefs.insert(db);
            }
            db.commit();
        } catch (Exception e) {
            try {
                db.rollback();
                e.printStackTrace(System.out);
                LOG.error("Preferences", e);
            } catch (Exception e2) {

            }
        } finally {
            try {
                db.setAutoCommit(true);
            } catch (Exception e2) {

            }
        }
    }
}

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

@Override
public void addModel(PageModel model) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {//from   www. j a va  2 s .c  o  m
        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:eionet.cr.dao.virtuoso.VirtuosoHarvestScriptDAO.java

/**
 * @see eionet.cr.dao.HarvestScriptDAO#activateDeactivate(java.util.List)
 *//*  ww w  .j  a v  a  2  s.  co m*/
@Override
public void activateDeactivate(List<Integer> ids) throws DAOException {

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

    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = getSQLConnection();
        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(ACTIVATE_DEACTIVATE_SQL);
        for (Integer id : ids) {
            stmt.setInt(1, id);
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
    } catch (SQLException e) {
        SQLUtil.rollback(conn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(stmt);
        SQLUtil.close(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 {//from   w w w  . j a v  a  2  s.  c  o 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:net.ontopia.topicmaps.db2tm.ChangelogTestCase.java

@Test
public void testFile() throws IOException, SQLException {
    // this particular test file is for FullRescanEventTest, and we don't
    // want to test it again here. we lack the -changelog.csv in any case.
    if ("EVENTS".equals(casename))
        return;/*w  w  w . ja va 2s  . co  m*/

    TestFileUtils.verifyDirectory(base, "out");

    String cfg = TestFileUtils.getTransferredTestInputFile(testdataDirectory, "in", "sync", casename + ".xml")
            .getPath();
    File tm = TestFileUtils.getTransferredTestInputFile(testdataDirectory, "in", "sync", casename + ".ltm");
    File out = TestFileUtils.getTestOutputFile(testdataDirectory, "out", casename + ".cxtm");
    String baseline = TestFileUtils.getTestInputFile(testdataDirectory, "in/sync/baseline", casename + ".cxtm");

    // Connect to the DB
    Connection conn = getConnection();
    Statement stm = conn.createStatement();

    // Load the starter data into the table
    importCSV(stm, casename, casename + "-before.csv");

    // Create the changelog table (DB2TM.add needs it), but leave it empty
    importCSV(stm, casename + "_changelog", casename + "-changelog.csv", false);

    // Import the topic map seed.
    TopicMapIF topicmap = ImportExportUtils.getReader(tm).read();

    // Extend the topic map seed with the the config file.
    DB2TM.add(cfg, topicmap);

    // Now load the database with the changed data
    importCSV(stm, casename, casename + "-after.csv");
    importCSV(stm, casename + "_changelog", casename + "-changelog.csv");
    conn.commit(); // necessary to avoid timeout from DB2TM connection

    // OK, now, finally, we can sync!
    DB2TM.sync(cfg, topicmap);

    // Canonicalize!
    new CanonicalXTMWriter(out).write(topicmap);

    // Check that the cxtm output matches the baseline.
    Assert.assertTrue("The canonicalized conversion from " + casename + " does not match the baseline: " + out
            + " " + baseline, TestFileUtils.compareFileToResource(out, baseline));
}

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

@Override
public void deleteAllRecords(String tableName) throws SQLException {
    release(); // Release any previous ResultSet
    String deleteQuery = "DELETE FROM " + tableName;
    Statement stmt = null;//from  www . j a v a2s  .  c o m
    try {
        Connection conn = getConnection();
        stmt = conn.createStatement();
        int updateCount = stmt.executeUpdate(deleteQuery);
        conn.commit();
        LOG.info("Deleted " + updateCount + " records from " + tableName);
    } catch (SQLException ex) {
        LOG.error("Unable to execute delete query: " + deleteQuery, ex);
        throw ex;
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                LOG.error("Unable to close statement", ex);
            }
        }
    }
}