Search in sources :

Example 1 with Statement

use of java.sql.Statement in project camel by apache.

the class DrillProducer method process.

@Override
public void process(final Exchange exchange) throws Exception {
    final String query = exchange.getIn().getHeader(DrillConstants.DRILL_QUERY, String.class);
    // check query
    Statement st = null;
    ResultSet rs = null;
    try {
        st = connection.createStatement();
        rs = st.executeQuery(query);
        exchange.getIn().setBody(endpoint.queryForList(rs));
    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            st.close();
        } catch (Exception e) {
        }
    }
}
Also used : Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) SQLException(java.sql.SQLException)

Example 2 with Statement

use of java.sql.Statement in project camel by apache.

the class IBatisTestSupport method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    // lets create the database...
    Connection connection = createConnection();
    Statement statement = connection.createStatement();
    statement.execute(getStatement());
    connection.commit();
    connection.close();
    if (createTestData()) {
        Account account1 = new Account();
        account1.setId(123);
        account1.setFirstName("James");
        account1.setLastName("Strachan");
        account1.setEmailAddress("TryGuessing@gmail.com");
        Account account2 = new Account();
        account2.setId(456);
        account2.setFirstName("Claus");
        account2.setLastName("Ibsen");
        account2.setEmailAddress("Noname@gmail.com");
        template.sendBody("ibatis:insertAccount?statementType=Insert", new Account[] { account1, account2 });
    }
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) Before(org.junit.Before)

Example 3 with Statement

use of java.sql.Statement in project camel by apache.

the class JdbcProducer method doCreateAndExecuteSqlStatement.

private boolean doCreateAndExecuteSqlStatement(Exchange exchange, String sql, Connection conn) throws Exception {
    Statement stmt = null;
    ResultSet rs = null;
    boolean shouldCloseResources = true;
    try {
        stmt = conn.createStatement();
        if (parameters != null && !parameters.isEmpty()) {
            Map<String, Object> copy = new HashMap<String, Object>(parameters);
            IntrospectionSupport.setProperties(stmt, copy);
        }
        LOG.debug("Executing JDBC Statement: {}", sql);
        Boolean shouldRetrieveGeneratedKeys = exchange.getIn().getHeader(JdbcConstants.JDBC_RETRIEVE_GENERATED_KEYS, false, Boolean.class);
        boolean stmtExecutionResult;
        if (shouldRetrieveGeneratedKeys) {
            Object expectedGeneratedColumns = exchange.getIn().getHeader(JdbcConstants.JDBC_GENERATED_COLUMNS);
            if (expectedGeneratedColumns == null) {
                stmtExecutionResult = stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
            } else if (expectedGeneratedColumns instanceof String[]) {
                stmtExecutionResult = stmt.execute(sql, (String[]) expectedGeneratedColumns);
            } else if (expectedGeneratedColumns instanceof int[]) {
                stmtExecutionResult = stmt.execute(sql, (int[]) expectedGeneratedColumns);
            } else {
                throw new IllegalArgumentException("Header specifying expected returning columns isn't an instance of String[] or int[] but " + expectedGeneratedColumns.getClass());
            }
        } else {
            stmtExecutionResult = stmt.execute(sql);
        }
        if (stmtExecutionResult) {
            rs = stmt.getResultSet();
            shouldCloseResources = setResultSet(exchange, conn, rs);
        } else {
            int updateCount = stmt.getUpdateCount();
            // preserve headers
            exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
            // and then set the new header
            exchange.getOut().setHeader(JdbcConstants.JDBC_UPDATE_COUNT, updateCount);
        }
        if (shouldRetrieveGeneratedKeys) {
            setGeneratedKeys(exchange, conn, stmt.getGeneratedKeys());
        }
    } finally {
        if (shouldCloseResources) {
            closeQuietly(rs);
            closeQuietly(stmt);
        }
    }
    return shouldCloseResources;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet)

Example 4 with Statement

use of java.sql.Statement in project groovy by apache.

the class Sql method eachRow.

/**
     * Performs the given SQL query calling the given <code>rowClosure</code> with each row of the result set starting at
     * the provided <code>offset</code>, and including up to <code>maxRows</code> number of rows.
     * The row will be a <code>GroovyResultSet</code> which is a <code>ResultSet</code>
     * that supports accessing the fields using property style notation and ordinal index values.
     * <p>
     * In addition, the <code>metaClosure</code> will be called once passing in the
     * <code>ResultSetMetaData</code> as argument.
     * <p>
     * Note that the underlying implementation is based on either invoking <code>ResultSet.absolute()</code>,
     * or if the ResultSet type is <code>ResultSet.TYPE_FORWARD_ONLY</code>, the <code>ResultSet.next()</code> method
     * is invoked equivalently.  The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect
     * on the initial positioning within the result set.
     * <p>
     * Note that different database and JDBC driver implementations may work differently with respect to this method.
     * Specifically, one should expect that <code>ResultSet.TYPE_FORWARD_ONLY</code> may be less efficient than a
     * "scrollable" type.
     * <p>
     * Resource handling is performed automatically where appropriate.
     *
     * @param sql         the sql statement
     * @param offset      the 1-based offset for the first row to be processed
     * @param maxRows     the maximum number of rows to be processed
     * @param metaClosure called for meta data (only once after sql execution)
     * @param rowClosure  called for each row with a GroovyResultSet
     * @throws SQLException if a database access error occurs
     */
public void eachRow(String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException {
    Connection connection = createConnection();
    Statement statement = null;
    ResultSet results = null;
    try {
        statement = getStatement(connection, sql);
        results = statement.executeQuery(sql);
        if (metaClosure != null)
            metaClosure.call(results.getMetaData());
        boolean cursorAtRow = moveCursor(results, offset);
        if (!cursorAtRow)
            return;
        GroovyResultSet groovyRS = new GroovyResultSetProxy(results).getImpl();
        int i = 0;
        while ((maxRows <= 0 || i++ < maxRows) && groovyRS.next()) {
            rowClosure.call(groovyRS);
        }
    } catch (SQLException e) {
        LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
        throw e;
    } finally {
        closeResources(connection, statement, results);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet)

Example 5 with Statement

use of java.sql.Statement in project groovy by apache.

the class Sql method execute.

/**
     * Executes the given piece of SQL.
     * Also calls the provided processResults Closure to process any ResultSet or UpdateCount results that executing the SQL might produce.
     * <p>
     * Example usages:
     * <pre>
     * boolean first = true
     * sql.execute "{call FindAllByFirst('J')}", { isResultSet, result ->
     *   if (first) {
     *     first = false
     *     assert !isResultSet && result == 0
     *   } else {
     *     assert isResultSet && result == [[ID:1, FIRSTNAME:'James', LASTNAME:'Strachan'], [ID:4, FIRSTNAME:'Jean', LASTNAME:'Gabin']]
     *   }
     * }
     * </pre>
     * <p>
     * Resource handling is performed automatically where appropriate.
     *
     * @param sql the SQL to execute
     * @param processResults a Closure which will be passed two parameters: either {@code true} plus a list of GroovyRowResult values
     *                       derived from {@code statement.getResultSet()} or {@code false} plus the update count from {@code statement.getUpdateCount()}.
     *                       The closure will be called for each result produced from executing the SQL.
     * @throws SQLException if a database access error occurs
     * @since 2.3.2
     */
public void execute(String sql, Closure processResults) throws SQLException {
    Connection connection = createConnection();
    Statement statement = null;
    try {
        statement = getStatement(connection, sql);
        boolean isResultSet = statement.execute(sql);
        int updateCount = statement.getUpdateCount();
        while (isResultSet || updateCount != -1) {
            if (processResults.getMaximumNumberOfParameters() != 2) {
                throw new SQLException("Incorrect number of parameters for processResults Closure");
            }
            if (isResultSet) {
                ResultSet resultSet = statement.getResultSet();
                List<GroovyRowResult> rowResult = resultSet == null ? null : asList(sql, resultSet);
                processResults.call(isResultSet, rowResult);
            } else {
                processResults.call(isResultSet, updateCount);
            }
            isResultSet = statement.getMoreResults();
            updateCount = statement.getUpdateCount();
        }
    } catch (SQLException e) {
        LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
        throw e;
    } finally {
        closeResources(connection, statement);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet)

Aggregations

Statement (java.sql.Statement)2195 Connection (java.sql.Connection)1082 ResultSet (java.sql.ResultSet)1081 PreparedStatement (java.sql.PreparedStatement)957 SQLException (java.sql.SQLException)911 Test (org.junit.Test)547 ArrayList (java.util.ArrayList)152 CallableStatement (java.sql.CallableStatement)128 ResultSetMetaData (java.sql.ResultSetMetaData)122 Properties (java.util.Properties)110 IOException (java.io.IOException)85 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)81 DruidPooledStatement (com.alibaba.druid.pool.DruidPooledStatement)71 DataSource (javax.sql.DataSource)62 HashMap (java.util.HashMap)61 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)56 DruidPooledConnection (com.alibaba.druid.pool.DruidPooledConnection)47 Context (javax.naming.Context)42 MockConnection (com.alibaba.druid.mock.MockConnection)41 DatabaseMetaData (java.sql.DatabaseMetaData)40