List of usage examples for java.sql Connection setAutoCommit
void setAutoCommit(boolean autoCommit) throws SQLException;
From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java
@Override public void add(Files fileInDb) { Connection con = null; PreparedStatement preparedStatement = null; try {/*ww w . j a v a 2 s . co m*/ con = DBConnector.getConnection(); con.setAutoCommit(false); preparedStatement = con.prepareStatement(getInsertByFiles(fileInDb)); preparedStatement.executeUpdate(); con.commit(); } catch (SQLException e) { handleException(e, con); } finally { doFinal(con, preparedStatement); } }
From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java
@Override public void add(StringBuilder fStat) { Connection con = null; PreparedStatement preparedStatement = null; try {/*from ww w . j a v a 2 s .com*/ con = DBConnector.getConnection(); con.setAutoCommit(false); preparedStatement = con.prepareStatement(fStat.toString()); preparedStatement.executeUpdate(); con.commit(); } catch (SQLException e) { handleException(e, con); } finally { doFinal(con, preparedStatement); } }
From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java
@Override public void update(Files fileInDb) { Connection con = null; PreparedStatement preparedStatement = null; try {/*from ww w. j av a 2s .co m*/ con = DBConnector.getConnection(); con.setAutoCommit(false); preparedStatement = con.prepareStatement(SqlGenerator.getUpdateByFiles(fileInDb)); preparedStatement.executeUpdate(); con.commit(); } catch (SQLException e) { handleException(e, con); } finally { doFinal(con, preparedStatement); } }
From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java
@Override public boolean saveAll(List<User> entities) { if (null != entities) { Connection conn = getConnection(); try {//from w w w. j a v a2s . c o m conn.setAutoCommit(false); for (User user : entities) { save(user); } conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } return super.saveAll(entities); }
From source file:com.fileanalyzer.dao.impl.FilesDAOImpl.java
@Override public void delete(Files fileInDb) { Connection con = null; Statement statement = null;/*from w w w . jav a 2 s. c o m*/ try { con = DBConnector.getConnection(); con.setAutoCommit(false); statement = con.createStatement(); statement.execute("delete from " + Files.FilesFieldsKey.TABLE + " where id=" + fileInDb.getId()); con.commit(); } catch (SQLException e) { handleException(e, con); } 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:dk.netarkivet.common.utils.DBUtils.java
/** * Prepare a statement for iteration given a query string, fetch size * and some args.// w ww.j a v a 2 s . c om * * NB: the provided connection is not closed. * * @param c a Database connection * @param fetchSize hint to JDBC driver on number of results to cache * @param query a query string (must not be null or empty) * @param args some args to insert into this query string (must not be null) * @return a prepared statement * @throws SQLException If unable to prepare a statement * @throws ArgumentNotValid If unable to handle type of one the args, or * the arguments are either null or an empty String. */ public static PreparedStatement prepareStatement(Connection c, int fetchSize, String query, Object... args) throws SQLException { ArgumentNotValid.checkNotNull(c, "Connection c"); ArgumentNotValid.checkPositive(fetchSize, "int fetchSize"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); c.setAutoCommit(false); PreparedStatement s = c.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); s.setFetchSize(fetchSize); int i = 1; for (Object arg : args) { if (arg instanceof String) { s.setString(i, (String) arg); } else if (arg instanceof Integer) { s.setInt(i, (Integer) arg); } else if (arg instanceof Long) { s.setLong(i, (Long) arg); } else if (arg instanceof Boolean) { s.setBoolean(i, (Boolean) arg); } else if (arg instanceof Date) { s.setTimestamp(i, new Timestamp(((Date) arg).getTime())); } else { throw new ArgumentNotValid("Cannot handle type '" + arg.getClass().getName() + "'. We can only handle string, " + "int, long, date or boolean args for query: " + query); } i++; } return s; }
From source file:io.apiman.gateway.engine.jdbc.PollCachingJdbcRegistry.java
/** * Stores a "dataversion" record in the ES store. There is only a single one of these. The * return value of the add will include the version number of the entity. This version * number is what we use to determine whether our cache is stale. *//*w w w . j ava 2 s. c o m*/ protected void updateDataVersion() { Connection conn = null; try { long newVersion = System.currentTimeMillis(); conn = ds.getConnection(); conn.setAutoCommit(false); QueryRunner run = new QueryRunner(); run.update(conn, "DELETE FROM gw_dataversion"); //$NON-NLS-1$ run.update(conn, "INSERT INTO gw_dataversion (version) VALUES (?)", //$NON-NLS-1$ newVersion); DbUtils.commitAndClose(conn); dataVersion = newVersion; } catch (SQLException e) { dataVersion = -1; } }
From source file:com.che.software.testato.domain.dao.jdbc.impl.VariantDAO.java
/** * Creates variants for a given test case. Is called after the variants * generation.//from w w w .java 2s . c o m * * @author Clement HELIOU (clement.heliou@che-software.com). * @param testCaseId the test case id. * @param variants the list of generated variants. * @since July, 2011. * @throws VariantCreationDAOException if an error occurs during the * creation. */ @Override public void createVariantsFromTestCaseId(int testCaseId, List<VariantCreation> variants) throws VariantCreationDAOException { LOGGER.debug("createVariantsFromTestCaseId(" + testCaseId + "," + variants.size() + " variants)"); Connection connection = null; try { connection = getDataSource().getConnection(); connection.setAutoCommit(false); for (VariantCreation variant : variants) { getQueryRunner().update(connection, "INSERT INTO variant(variant_id, variant_type, test_case_id, label, quantitative_criterion) VALUES(nextval('variant_id_seq'),?,?,NULL,NULL) ", new Object[] { variant.getVariantType().name(), testCaseId }); Integer createdVariantId = (Integer) getQueryRunner().query(connection, "SELECT MAX(variant_id)::int AS result FROM variant ", new ScalarHandler("result")); for (Element element : variant.getElements()) { getQueryRunner().update(connection, "INSERT INTO variant_element(element_id, variant_id) VALUES(?,?) ", new Object[] { element.getElementId(), createdVariantId }); } for (ProceduralArrow transition : variant.getTransitions()) { getQueryRunner().update(connection, "INSERT INTO variant_transition(transition_id, variant_id) VALUES(?,?) ", new Object[] { transition.getTransitionId(), createdVariantId }); } } connection.commit(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { throw new VariantCreationDAOException(e1); } throw new VariantCreationDAOException(e); } finally { if (null != connection) { DbUtils.closeQuietly(connection); } } }
From source file:com.googlecode.psiprobe.controllers.sql.ExecuteSqlController.java
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request, HttpServletResponse response) throws Exception { String resourceName = ServletRequestUtils.getStringParameter(request, "resource"); String sql = ServletRequestUtils.getStringParameter(request, "sql", null); if (sql == null || sql.equals("") || sql.trim().equals("")) { request.setAttribute("errorMessage", getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.required")); return new ModelAndView(getViewName()); }//from www.j a v a2 s.c o m int maxRows = ServletRequestUtils.getIntParameter(request, "maxRows", 0); int rowsPerPage = ServletRequestUtils.getIntParameter(request, "rowsPerPage", 0); int historySize = ServletRequestUtils.getIntParameter(request, "historySize", 0); // store current option values and query history in a session attribute HttpSession sess = request.getSession(); DataSourceTestInfo sessData = (DataSourceTestInfo) sess.getAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR); synchronized (sess) { if (sessData == null) { sessData = new DataSourceTestInfo(); sess.setAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR, sessData); } sessData.setMaxRows(maxRows); sessData.setRowsPerPage(rowsPerPage); sessData.setHistorySize(historySize); sessData.addQueryToHistory(sql); } DataSource dataSource = null; try { dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName, getContainerWrapper()); } catch (NamingException e) { request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName })); } if (dataSource == null) { request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName })); } else { List results = null; int rowsAffected = 0; try { // TODO: use Spring's jdbc template? Connection conn = dataSource.getConnection(); try { conn.setAutoCommit(true); PreparedStatement stmt = conn.prepareStatement(sql); try { boolean hasResultSet = stmt.execute(); if (!hasResultSet) { rowsAffected = stmt.getUpdateCount(); } else { results = new ArrayList(); ResultSet rs = stmt.getResultSet(); try { ResultSetMetaData metaData = rs.getMetaData(); while (rs.next() && (maxRows < 0 || results.size() < maxRows)) { Map record = new LinkedHashMap(); for (int i = 1; i <= metaData.getColumnCount(); i++) { String value = rs.getString(i); if (rs.wasNull()) { value = getMessageSourceAccessor() .getMessage("probe.src.dataSourceTest.sql.null"); } else { value = HtmlUtils.htmlEscape(value); } // a work around for IE browsers bug of not displaying // a border around an empty table column if (value.equals("")) { value = " "; } // Pad the keys of columns with existing labels so they are distinct String key = metaData.getColumnLabel(i); while (record.containsKey(key)) { key += " "; } record.put(HtmlUtils.htmlEscape(key), value); } results.add(record); } } finally { rs.close(); } rowsAffected = results.size(); } } finally { stmt.close(); } } finally { conn.close(); } // store the query results in the session attribute in order // to support a result set pagination feature without re-executing the query synchronized (sess) { sessData.setResults(results); } ModelAndView mv = new ModelAndView(getViewName(), "results", results); mv.addObject("rowsAffected", String.valueOf(rowsAffected)); mv.addObject("rowsPerPage", String.valueOf(rowsPerPage)); return mv; } catch (SQLException e) { String message = getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.failure", new Object[] { e.getMessage() }); logger.error(message, e); request.setAttribute("errorMessage", message); } } return new ModelAndView(getViewName()); }
From source file:com.taobao.datax.plugins.reader.postgrereader.PostgreReader.java
@Override public int startRead(LineSender lineSender) { DBResultSetSender proxy = DBResultSetSender.newSender(lineSender); proxy.setMonitor(getMonitor());/* w w w . j a va 2 s.c o m*/ proxy.setDateFormatMap(genDateFormatMap()); String sql = param.getValue(ParamKey.sql); logger.info(String.format("PostgreReader start to query %s .", sql)); ResultSet rs = null; Connection connection = null; try { connection = getCon(); connection.setAutoCommit(false); Statement stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); logger.info("set postgre statement fetch size"); stmt.setFetchSize(fetchSize); logger.info("connection info autoCommit:" + connection.getAutoCommit() + " fetchSize" + stmt.getFetchSize()); rs = DBUtils.query(stmt, sql); logger.info("get a ResultSet"); proxy.sendToWriter(rs); logger.info("send to writer"); proxy.flush(); getMonitor().setStatus(PluginStatus.READ_OVER); return PluginStatus.SUCCESS.value(); } catch (SQLException e) { logger.error(ExceptionTracker.trace(e)); throw new DataExchangeException(e); } finally { if (null != rs) { DBUtils.closeResultSet(rs); } if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }