Search in sources :

Example 41 with CallableStatement

use of java.sql.CallableStatement in project hibernate-orm by hibernate.

the class AttributeConverterSqlTypeDescriptorAdapter method getBinder.

// Binding ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
@SuppressWarnings("unchecked")
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
    // Get the binder for the intermediate type representation
    final ValueBinder realBinder = delegate.getBinder(intermediateJavaTypeDescriptor);
    return new ValueBinder<X>() {

        @Override
        public void bind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
            final Object convertedValue;
            try {
                convertedValue = converter.convertToDatabaseColumn(value);
            } catch (PersistenceException pe) {
                throw pe;
            } catch (RuntimeException re) {
                throw new PersistenceException("Error attempting to apply AttributeConverter", re);
            }
            log.debugf("Converted value on binding : %s -> %s", value, convertedValue);
            realBinder.bind(st, convertedValue, index, options);
        }

        @Override
        public void bind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException {
            final Object convertedValue;
            try {
                convertedValue = converter.convertToDatabaseColumn(value);
            } catch (PersistenceException pe) {
                throw pe;
            } catch (RuntimeException re) {
                throw new PersistenceException("Error attempting to apply AttributeConverter", re);
            }
            log.debugf("Converted value on binding : %s -> %s", value, convertedValue);
            realBinder.bind(st, convertedValue, name, options);
        }
    };
}
Also used : CallableStatement(java.sql.CallableStatement) WrapperOptions(org.hibernate.type.descriptor.WrapperOptions) PersistenceException(javax.persistence.PersistenceException) PreparedStatement(java.sql.PreparedStatement) ValueBinder(org.hibernate.type.descriptor.ValueBinder)

Example 42 with CallableStatement

use of java.sql.CallableStatement in project tomcat by apache.

the class TestSlowQueryReport method testSlowSqlJmx.

@Test
public void testSlowSqlJmx() throws Exception {
    int count = 1;
    Connection con = this.datasource.getConnection();
    for (int i = 0; i < count; i++) {
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(superSlowSql);
        rs.close();
        st.close();
    }
    Map<String, SlowQueryReport.QueryStats> map = SlowQueryReport.getPoolStats(datasource.getPool().getName());
    Assert.assertNotNull(map);
    Assert.assertEquals(1, map.size());
    String key = map.keySet().iterator().next();
    SlowQueryReport.QueryStats stats = map.get(key);
    System.out.println("Stats:" + stats);
    ClientListener listener = new ClientListener();
    ConnectionPool pool = datasource.getPool();
    ManagementFactory.getPlatformMBeanServer().addNotificationListener(new SlowQueryReportJmx().getObjectName(SlowQueryReportJmx.class, pool.getName()), listener, null, null);
    for (int i = 0; i < count; i++) {
        PreparedStatement st = con.prepareStatement(superSlowSql);
        ResultSet rs = st.executeQuery();
        rs.close();
        st.close();
    }
    System.out.println("Stats:" + stats);
    for (int i = 0; i < count; i++) {
        CallableStatement st = con.prepareCall(superSlowSql);
        ResultSet rs = st.executeQuery();
        rs.close();
        st.close();
    }
    System.out.println("Stats:" + stats);
    Assert.assertEquals("Expecting to have received " + (2 * count) + " notifications.", 2 * count, listener.notificationCount.get());
    con.close();
    tearDown();
    //make sure we actually did clean up when the pool closed
    Assert.assertNull(SlowQueryReport.getPoolStats(pool.getName()));
}
Also used : ConnectionPool(org.apache.tomcat.jdbc.pool.ConnectionPool) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) SlowQueryReportJmx(org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmx) SlowQueryReport(org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReport) CallableStatement(java.sql.CallableStatement) ResultSet(java.sql.ResultSet) Test(org.junit.Test)

Example 43 with CallableStatement

use of java.sql.CallableStatement in project elasticsearch-jdbc by jprante.

the class StandardSource method executeCallable.

/**
     * Execute callable SQL command
     *
     * @param command the SQL command
     * @throws SQLException when SQL execution gives an error
     * @throws IOException  when input/output error occurs
     */
private void executeCallable(SQLCommand command) throws Exception {
    // call stored procedure
    CallableStatement statement = null;
    try {
        // we do not make a difference betwwen read/write and we assume
        // it is safe to use the read connection and query the DB
        Connection connection = getConnectionForWriting();
        logger.debug("{} using write connection {} for executing callable statement", this, connection);
        if (connection != null) {
            statement = connection.prepareCall(command.getSQL());
            if (!command.getParameters().isEmpty()) {
                bind(statement, command.getParameters());
            }
            if (!command.getRegister().isEmpty()) {
                register(statement, command.getRegister());
            }
            boolean hasRows = statement.execute();
            SinkKeyValueStreamListener<Object, Object> listener = new SinkKeyValueStreamListener<Object, Object>().output(context.getSink());
            if (hasRows) {
                logger.debug("callable execution created result set");
                while (hasRows) {
                    // merge result set, but use register
                    merge(command, statement.getResultSet(), listener);
                    hasRows = statement.getMoreResults();
                }
            } else {
                // no result set, merge from registered params only
                merge(command, statement, listener);
            }
        }
    } finally {
        close(statement);
    }
}
Also used : CallableStatement(java.sql.CallableStatement) Connection(java.sql.Connection)

Example 44 with CallableStatement

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

the class Sql method setObject.

/**
     * Strategy method allowing derived classes to handle types differently
     * such as for CLOBs etc.
     *
     * @param statement the statement of interest
     * @param i         the index of the object of interest
     * @param value     the new object value
     * @throws SQLException if a database access error occurs
     */
protected void setObject(PreparedStatement statement, int i, Object value) throws SQLException {
    if (value instanceof InParameter || value instanceof OutParameter) {
        if (value instanceof InParameter) {
            InParameter in = (InParameter) value;
            Object val = in.getValue();
            if (null == val) {
                statement.setNull(i, in.getType());
            } else {
                statement.setObject(i, val, in.getType());
            }
        }
        if (value instanceof OutParameter) {
            try {
                OutParameter out = (OutParameter) value;
                ((CallableStatement) statement).registerOutParameter(i, out.getType());
            } catch (ClassCastException e) {
                throw new SQLException("Cannot register out parameter.");
            }
        }
    } else {
        try {
            statement.setObject(i, value);
        } catch (SQLException e) {
            if (value == null) {
                SQLException se = new SQLException("Your JDBC driver may not support null arguments for setObject. Consider using Groovy's InParameter feature." + (e.getMessage() == null ? "" : " (CAUSE: " + e.getMessage() + ")"));
                se.setNextException(e);
                throw se;
            } else {
                throw e;
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) CallableStatement(java.sql.CallableStatement)

Example 45 with CallableStatement

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

the class Sql method callWithRows.

/**
     * Base internal method for call(), callWithRows(), and callWithAllRows() style of methods.
     * <p>
     * Performs a stored procedure call with the given parameters,
     * calling the closure once with all result objects,
     * and also returning the rows of the ResultSet(s) (if processResultSets is set to
     * Sql.FIRST_RESULT_SET, Sql.ALL_RESULT_SETS)
     * <p>
     * Main purpose of processResultSets param is to retain original call() method
     * performance when this is set to Sql.NO_RESULT_SETS
     * <p>
     * Resource handling is performed automatically where appropriate.
     *
     * @param sql     the sql statement
     * @param params  a list of parameters
     * @param processResultsSets the result sets to process, either Sql.NO_RESULT_SETS, Sql.FIRST_RESULT_SET, or Sql.ALL_RESULT_SETS
     * @param closure called once with all out parameter results
     * @return a list of GroovyRowResult objects
     * @throws SQLException if a database access error occurs
     * @see #callWithRows(String, List, Closure)
     */
protected List<List<GroovyRowResult>> callWithRows(String sql, List<Object> params, int processResultsSets, Closure closure) throws SQLException {
    Connection connection = createConnection();
    CallableStatement statement = null;
    List<GroovyResultSet> resultSetResources = new ArrayList<GroovyResultSet>();
    try {
        statement = getCallableStatement(connection, sql, params);
        boolean hasResultSet = statement.execute();
        List<Object> results = new ArrayList<Object>();
        int indx = 0;
        int inouts = 0;
        for (Object value : params) {
            if (value instanceof OutParameter) {
                if (value instanceof ResultSetOutParameter) {
                    GroovyResultSet resultSet = CallResultSet.getImpl(statement, indx);
                    resultSetResources.add(resultSet);
                    results.add(resultSet);
                } else {
                    Object o = statement.getObject(indx + 1);
                    if (o instanceof ResultSet) {
                        GroovyResultSet resultSet = new GroovyResultSetProxy((ResultSet) o).getImpl();
                        results.add(resultSet);
                        resultSetResources.add(resultSet);
                    } else {
                        results.add(o);
                    }
                }
                inouts++;
            }
            indx++;
        }
        closure.call(results.toArray(new Object[inouts]));
        List<List<GroovyRowResult>> resultSets = new ArrayList<List<GroovyRowResult>>();
        if (processResultsSets == NO_RESULT_SETS) {
            resultSets.add(new ArrayList<GroovyRowResult>());
            return resultSets;
        }
        //Check both hasResultSet and getMoreResults() because of differences in vendor behavior
        if (!hasResultSet) {
            hasResultSet = statement.getMoreResults();
        }
        while (hasResultSet && (processResultsSets != NO_RESULT_SETS)) {
            resultSets.add(asList(sql, statement.getResultSet()));
            if (processResultsSets == FIRST_RESULT_SET) {
                break;
            } else {
                hasResultSet = statement.getMoreResults();
            }
        }
        return resultSets;
    } catch (SQLException e) {
        LOG.warning("Failed to execute: " + sql + " because: " + e.getMessage());
        throw e;
    } finally {
        for (GroovyResultSet rs : resultSetResources) {
            closeResources(null, null, rs);
        }
        closeResources(connection, statement);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) CallableStatement(java.sql.CallableStatement) ResultSet(java.sql.ResultSet)

Aggregations

CallableStatement (java.sql.CallableStatement)273 SQLException (java.sql.SQLException)138 Connection (java.sql.Connection)125 ResultSet (java.sql.ResultSet)60 DatabaseAccessException (com.axway.ats.log.autodb.exceptions.DatabaseAccessException)45 DbConnection (com.axway.ats.core.dbaccess.DbConnection)28 Checkpoint (com.axway.ats.log.autodb.entities.Checkpoint)22 ArrayList (java.util.ArrayList)22 PreparedStatement (java.sql.PreparedStatement)21 CouldntSaveDataException (com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException)20 Timestamp (java.sql.Timestamp)18 Test (org.junit.Test)16 CouldntDeleteException (com.google.security.zynamics.binnavi.Database.Exceptions.CouldntDeleteException)15 Statement (java.sql.Statement)14 HashMap (java.util.HashMap)10 CConnection (com.google.security.zynamics.binnavi.Database.CConnection)8 MockCallableStatement (com.alibaba.druid.mock.MockCallableStatement)7 MaybeNullException (com.google.security.zynamics.binnavi.Exceptions.MaybeNullException)6 BigInteger (java.math.BigInteger)6 OracleCallableStatement (oracle.jdbc.OracleCallableStatement)6