List of usage examples for org.apache.commons.dbutils ResultSetHandler handle
T handle(ResultSet rs) throws SQLException;
ResultSet
into an Object. From source file:de.tu_berlin.dima.oligos.db.JdbcConnector.java
/** * Retrieves all foreign keys / references between the first and the second * table.//from w w w .j a v a 2s .com * @param firstTable The first table * @param secondTable The second table * @return all foreign keys between the first and the second table * @throws SQLException if a database access error occurs * @since 0.3.1 * @see {@link ForeignKey} */ public Set<ForeignKey> getCrossReferences(final TableRef firstTable, final TableRef secondTable) throws SQLException { Set<ForeignKey> fKeys = Sets.newHashSet(); ResultSetHandler<Set<ForeignKey>> handler = new ForeignKeysHandler(); String firstS = firstTable.getSchemaName(); String firstT = firstTable.getTableName(); String secondS = secondTable.getSchemaName(); String secondT = secondTable.getTableName(); ResultSet rs1 = metaData.getCrossReference(null, firstS, firstT, null, secondS, secondT); ResultSet rs2 = metaData.getCrossReference(null, secondS, secondT, null, firstS, firstT); fKeys.addAll(handler.handle(rs1)); fKeys.addAll(handler.handle(rs2)); return fKeys; }
From source file:com.untzuntz.coredata.QueryRunner.java
/** * Calls query after checking the parameters to ensure nothing is null. * @param conn The connection to use for the query call. * @param closeConn True if the connection should be closed, false otherwise. * @param sql The SQL statement to execute. * @param params An array of query replacement parameters. Each row in * this array is one set of batch replacement values. * @return The results of the query.//from ww w . java2 s . co m * @throws SQLException If there are database or parameter errors. */ private <T> T query(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (rsh == null) { if (closeConn) { close(conn); } throw new SQLException("Null ResultSetHandler"); } PreparedStatement stmt = null; ResultSet rs = null; T result = null; try { stmt = this.prepareStatement(conn, sql); this.fillStatement(stmt, params); rs = this.wrap(stmt.executeQuery()); result = rsh.handle(rs); } catch (SQLException e) { this.rethrow(e, sql, params); } finally { try { close(rs); } finally { close(stmt); if (closeConn) { close(conn); } } } return result; }
From source file:com.untzuntz.coredata.QueryRunner.java
private <T> T insert(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); }/*from ww w .j av a 2 s. c o m*/ if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (rsh == null) { if (closeConn) { close(conn); } throw new SQLException("Null ResultSetHandler"); } PreparedStatement stmt = null; T generatedKeys = null; try { stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.fillStatement(stmt, params); stmt.executeUpdate(); ResultSet resultSet = stmt.getGeneratedKeys(); generatedKeys = rsh.handle(resultSet); } catch (SQLException e) { this.rethrow(e, sql, params); } finally { close(stmt); if (closeConn) { close(conn); } } return generatedKeys; }
From source file:org.apache.lens.server.query.LensServerDAO.java
private <T> List<T> findInternal(List<QueryStatus.Status> states, String user, String driverName, String queryName, long fromDate, long toDate, final ResultSetHandler<T> handler, String projection) throws LensException { StringBuilder builder = new StringBuilder("SELECT " + projection + " FROM finished_queries"); List<Object> params = new ArrayList<>(3); builder.append(" WHERE "); List<String> filters = new ArrayList<>(3); if (states != null && !states.isEmpty()) { StringBuilder statusFilterBuilder = new StringBuilder("status in ("); String sep = ""; for (QueryStatus.Status status : states) { statusFilterBuilder.append(sep).append("?"); sep = ", "; params.add(status.toString()); }/* w ww . ja v a 2s. c o m*/ filters.add(statusFilterBuilder.append(")").toString()); } if (StringUtils.isNotBlank(user)) { filters.add("submitter=?"); params.add(user); } if (StringUtils.isNotBlank(queryName)) { filters.add("queryname like ?"); params.add("%" + queryName + "%"); } if (StringUtils.isNotBlank(driverName)) { filters.add("lower(drivername)=?"); params.add(driverName.toLowerCase()); } filters.add("submissiontime BETWEEN ? AND ?"); params.add(fromDate); params.add(toDate); builder.append(StringUtils.join(filters, " AND ")); ResultSetHandler<List<T>> resultSetHandler = new ResultSetHandler<List<T>>() { @Override public List<T> handle(ResultSet resultSet) throws SQLException { List<T> results = new ArrayList<T>(); while (resultSet.next()) { try { results.add(handler.handle(resultSet)); } catch (RuntimeException e) { log.warn("Unable to handle row " + LensServerDAO.toString(resultSet), e); } } return results; } }; QueryRunner runner = new QueryRunner(ds); String query = builder.toString(); try { return runner.query(query, resultSetHandler, params.toArray()); } catch (SQLException e) { throw new LensException(e); } }
From source file:org.batoo.jpa.core.impl.jdbc.dbutils.QueryRunner.java
/** * Calls query after checking the parameters to ensure nothing is null. * /*from www .j a v a 2s.c o m*/ * @param conn * The connection to use for the query call. * @param closeConn * True if the connection should be closed, false otherwise. * @param sql * The SQL statement to execute. * @param params * An array of query replacement parameters. Each row in this array is one set of batch replacement values. * @return The results of the query. * @throws SQLException * If there are database or parameter errors. */ private <T> T query(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { this.close(conn); } throw new SQLException("Null SQL statement"); } if (rsh == null) { if (closeConn) { this.close(conn); } throw new SQLException("Null ResultSetHandler"); } PreparedStatement stmt = null; ResultSet rs = null; T result = null; try { stmt = this.prepareStatement(conn, sql); this.fillStatement(stmt, params); rs = this.wrap(stmt.executeQuery()); result = rsh.handle(rs); } catch (final SQLException e) { this.rethrow(e, sql, params); } finally { try { this.close(rs); } finally { this.close(stmt); if (closeConn) { this.close(conn); } } } return result; }
From source file:org.batoo.jpa.jdbc.dbutils.QueryRunner.java
/** * Calls query after checking the parameters to ensure nothing is null. * //ww w .j a v a 2s . c o m * @param conn * The connection to use for the query call. * @param closeConn * True if the connection should be closed, false otherwise. * @param sql * The SQL statement to execute. * @param params * An array of query replacement parameters. Each row in this array is one set of batch replacement values. * @return The results of the query. * @throws SQLException * If there are database or parameter errors. */ private <T> T query(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { PreparedStatement statement = null; ResultSet resultSet = null; try { statement = conn.prepareStatement(sql); if (params != null) { this.fillStatement(statement, params); } resultSet = statement.executeQuery(); return rsh.handle(resultSet); } catch (final SQLException e) { throw this.convertSqlException(e, sql, params); } finally { try { DbUtils.close(resultSet); } finally { DbUtils.close(statement); if (closeConn) { DbUtils.close(conn); } } } }
From source file:org.bidtime.dbutils.QueryRunnerEx.java
/** * Calls query after checking the parameters to ensure nothing is null. * @param conn The connection to use for the query call. * @param closeConn True if the connection should be closed, false otherwise. * @param sql The SQL statement to execute. * @param params An array of query replacement parameters. Each row in * this array is one set of batch replacement values. * @return The results of the query./*from w ww . j av a 2s.c o m*/ * @throws SQLException If there are database or parameter errors. */ private <T> T query(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (rsh == null) { if (closeConn) { close(conn); } throw new SQLException("Null ResultSetHandler"); } PreparedStatement stmt = null; ResultSet rs = null; T result = null; long startTime = System.currentTimeMillis(); try { //stmt = this.prepareStatement(conn, sql); stmt = (PreparedStatement) conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(StmtParams.getInstance().getFetchSize()); stmt.setFetchDirection(ResultSet.FETCH_REVERSE); stmt.setQueryTimeout(StmtParams.getInstance().getStmtQueryTimeOut()); this.fillStatement(stmt, params); rs = this.wrap(stmt.executeQuery()); result = rsh.handle(rs); } catch (SQLException e) { this.rethrow(e, sql, params); } finally { try { close(rs); } finally { close(stmt); if (closeConn) { close(conn); } } if (LogSelectSql.logInfoOrDebug()) { LogSelectSql.logFormatTimeNow(startTime, sql, params); } } return result; }
From source file:org.bidtime.dbutils.QueryRunnerEx.java
/** * Executes the given INSERT SQL statement. * @param conn The connection to use for the query call. * @param closeConn True if the connection should be closed, false otherwise. * @param sql The SQL statement to execute. * @param rsh The handler used to create the result object from * the <code>ResultSet</code> of auto-generated keys. * @param params The query replacement parameters. * @return An object generated by the handler. * @throws SQLException If there are database or parameter errors. * @since 1.6//from w ww . j a v a 2 s .c o m */ private <T> T insert(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (rsh == null) { if (closeConn) { close(conn); } throw new SQLException("Null ResultSetHandler"); } PreparedStatement stmt = null; long startTime = System.currentTimeMillis(); T generatedKeys = null; try { stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setQueryTimeout(StmtParams.getInstance().getStmtUpdateTimeOut()); this.fillStatement(stmt, params); stmt.executeUpdate(); ResultSet resultSet = stmt.getGeneratedKeys(); generatedKeys = rsh.handle(resultSet); } catch (SQLException e) { this.rethrow(e, sql, params); } finally { close(stmt); if (closeConn) { close(conn); } if (LogInsertSql.logInfoOrDebug()) { LogInsertSql.logFormatTimeNow(startTime, sql, params); } } return generatedKeys; }
From source file:org.bidtime.dbutils.QueryRunnerEx.java
/** * Executes the given batch of INSERT SQL statements. * @param conn The connection to use for the query call. * @param closeConn True if the connection should be closed, false otherwise. * @param sql The SQL statement to execute. * @param rsh The handler used to create the result object from * the <code>ResultSet</code> of auto-generated keys. * @param params The query replacement parameters. * @return The result generated by the handler. * @throws SQLException If there are database or parameter errors. * @since 1.6//from w w w .j a va 2 s . c o m */ private <T> T insertBatch(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object[][] params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (params == null) { if (closeConn) { close(conn); } throw new SQLException("Null parameters. If parameters aren't need, pass an empty array."); } PreparedStatement stmt = null; long startTime = System.currentTimeMillis(); T generatedKeys = null; try { stmt = this.prepareStatement(conn, sql, Statement.RETURN_GENERATED_KEYS); stmt.setQueryTimeout(StmtParams.getInstance().getStmtBatchTimeOut()); for (int i = 0; i < params.length; i++) { this.fillStatement(stmt, params[i]); stmt.addBatch(); } stmt.executeBatch(); ResultSet rs = stmt.getGeneratedKeys(); generatedKeys = rsh.handle(rs); } catch (SQLException e) { this.rethrow(e, sql, (Object[]) params); } finally { close(stmt); if (closeConn) { close(conn); } if (LogInsertSql.logInfoOrDebug()) { LogInsertSql.logFormatTimeNow(startTime, sql, params); } } return generatedKeys; }
From source file:org.openconcerto.sql.model.SQLDataSource.java
/** * Execute <code>query</code> within <code>c</code>, passing the result set to <code>rsh</code>. * /* w w w .ja va 2 s.co m*/ * @param query the query to perform. * @param rsh what to do with the result, can be <code>null</code>. * @param changeState whether <code>query</code> changes the state of a connection. * @param passedConn the sql connection to use. * @return the result of <code>rsh</code>, <code>null</code> if rsh or the resultSet is * <code>null</code>. * @throws RTInterruptedException if the current thread is interrupted while waiting for the * cache or for the database. */ private Object execute(final String query, final ResultSetHandler rsh, final boolean changeState, final Connection passedConn) throws RTInterruptedException { final long timeMs = System.currentTimeMillis(); final long time = System.nanoTime(); // some systems refuse to execute nothing if (query.length() == 0) { SQLRequestLog.log(query, "Pas de requte.", timeMs, time); return null; } final IResultSetHandler irsh = rsh instanceof IResultSetHandler ? (IResultSetHandler) rsh : null; final SQLCache<List<?>, Object> cache; synchronized (this) { // transactions are isolated from one another, so their caches should be too final HandlersStack handlersStack = getHandlersStack(); if (handlersStack != null && handlersStack.getCache() != null) cache = handlersStack.getCache(); else cache = this.cache; } final List<Object> key = cache != null && query.startsWith("SELECT") ? Arrays.asList(new Object[] { query, rsh }) : null; if (key != null && (irsh == null || irsh.readCache())) { final CacheResult<Object> l = cache.check(key); if (l.getState() == CacheResult.State.INTERRUPTED) throw new RTInterruptedException("interrupted while waiting for the cache"); else if (l.getState() == CacheResult.State.VALID) { // cache actif if (State.DEBUG) State.INSTANCE.addCacheHit(); SQLRequestLog.log(query, "En cache.", timeMs, time); return l.getRes(); } } Object result = null; QueryInfo info = null; final long afterCache = System.nanoTime(); final long afterQueryInfo, afterExecute, afterHandle; try { info = new QueryInfo(query, changeState, passedConn); try { afterQueryInfo = System.nanoTime(); final Object[] res = this.executeTwice(info); final Statement stmt = (Statement) res[0]; ResultSet rs = (ResultSet) res[1]; // TODO 1. rename #execute(String) to #executeN(String) // and make #execute(String) do #execute(String, null) // 2. let null rs pass to rsh // otherwise you write ds.execute("req", new ResultSetHandler() { // public Object handle(ResultSet rs) throws SQLException { // return "OK"; // } // }); // and OK won't be returned if "req" returns a null rs. afterExecute = System.nanoTime(); if (rsh != null && rs != null) { if (this.getSystem() == SQLSystem.DERBY || this.getSystem() == SQLSystem.POSTGRESQL) { rs = new SQLResultSet(rs); } result = rsh.handle(rs); } afterHandle = System.nanoTime(); stmt.close(); // if key was added to the cache if (key != null) { synchronized (this) { putInCache(cache, irsh, key, result, true); } } info.releaseConnection(); } catch (SQLException exn) { // don't usually do a getSchema() as it access the db throw new IllegalStateException("Impossible d'accder au rsultat de " + query + "\n in " + this, exn); } } catch (RuntimeException e) { // for each #check() there must be a #removeRunning() // let the cache know we ain't gonna tell it the result if (cache != null && key != null) cache.removeRunning(key); if (info != null) info.releaseConnection(e); throw e; } SQLRequestLog.log(query, "", info.getConnection(), timeMs, time, afterCache, afterQueryInfo, afterExecute, afterHandle, System.nanoTime()); return result; }