Example usage for java.sql PreparedStatement setObject

List of usage examples for java.sql PreparedStatement setObject

Introduction

In this page you can find the example usage for java.sql PreparedStatement setObject.

Prototype

void setObject(int parameterIndex, Object x) throws SQLException;

Source Link

Document

Sets the value of the designated parameter using the given object.

Usage

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

private GeneratedKey insertWithGeneratedKeyReturn(Object record, boolean useDeclaredOnly) {
    PreparedStatement st = null;
    boolean inTrans = inTransaction();
    String command = null;/* w  w  w  . j a  va2s  . co m*/
    int batchCount = 0;
    GeneratedKey gk = null;
    if (!inTrans)
        startTransaction();
    try {
        Class objClass = record.getClass();
        String schema = getEntitySchema(objClass);
        Boolean isCamelCased = useCamelCase(objClass);
        HashMap<Method, String> fieldMapping = getFieldMapping(objClass, GET, isCamelCased, useDeclaredOnly);
        String idFieldName = getIdFieldName(fieldMapping);
        HashMap<Integer, Method> indexMapping = new HashMap();
        String tableName = getTableName(objClass);
        if (tableName == null)
            tableName = getDbName(isCamelCased, objClass.getSimpleName(), null);
        command = getInsertCommand(tableName, schema, fieldMapping, indexMapping);
        if (idFieldName != null) {
            st = conn.prepareStatement(command, new String[] { idFieldName });
        } else {
            st = conn.prepareStatement(command);
        }
        for (int index : indexMapping.keySet()) {
            Object value = indexMapping.get(index).invoke(record, null);
            if (value instanceof java.util.Date) {
                value = new java.sql.Date(((java.util.Date) value).getTime());
            }
            st.setObject((Integer) index, value);
        }
        st.execute();
        ResultSet rs = st.getGeneratedKeys();
        if (rs.next()) {
            gk = new GeneratedKey(idFieldName, rs.getObject(1));
        }
        if (!inTrans)
            commitTransaction();
        return gk;
    } catch (Exception ex) {
        ex.printStackTrace();
        if (!inTrans)
            rollbackTransaction();
        throw new NativeQueryException(command, "insertWithGeneratedKeyReturn", ex);
    } finally {
        if (st != null) {
            try {
                st.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

private void doTestStrings(JdbcTemplateCallback jdbcTemplateCallback, boolean usePreparedStatement,
        Integer fetchSize, Integer maxRows, Integer queryTimeout, Object argument) throws Exception {

    String sql = "SELECT FORENAME FROM CUSTMR";
    String[] results = { "rod", "gary", " portia" };

    class StringHandler implements RowCallbackHandler {
        private List list = new LinkedList();

        public void processRow(ResultSet rs) throws SQLException {
            list.add(rs.getString(1));//w w w . j a v  a2 s  .  c om
        }

        public String[] getStrings() {
            return (String[]) list.toArray(new String[list.size()]);
        }
    }

    MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
    ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getString(1);
    ctrlResultSet.setReturnValue(results[0]);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getString(1);
    ctrlResultSet.setReturnValue(results[1]);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getString(1);
    ctrlResultSet.setReturnValue(results[2]);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock();
    if (fetchSize != null) {
        mockStatement.setFetchSize(fetchSize.intValue());
    }
    if (maxRows != null) {
        mockStatement.setMaxRows(maxRows.intValue());
    }
    if (queryTimeout != null) {
        mockStatement.setQueryTimeout(queryTimeout.intValue());
    }
    if (argument != null) {
        mockStatement.setObject(1, argument);
    }
    if (usePreparedStatement) {
        mockStatement.executeQuery();
    } else {
        mockStatement.executeQuery(sql);
    }
    ctrlStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockStatement.getWarnings();
        ctrlStatement.setReturnValue(null);
    }
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    if (usePreparedStatement) {
        mockConnection.prepareStatement(sql);
    } else {
        mockConnection.createStatement();
    }
    ctrlConnection.setReturnValue(mockStatement);

    ctrlResultSet.replay();
    ctrlStatement.replay();
    replay();

    StringHandler sh = new StringHandler();
    JdbcTemplate template = new JdbcTemplate();
    template.setDataSource(mockDataSource);
    if (fetchSize != null) {
        template.setFetchSize(fetchSize.intValue());
    }
    if (maxRows != null) {
        template.setMaxRows(maxRows.intValue());
    }
    if (queryTimeout != null) {
        template.setQueryTimeout(queryTimeout.intValue());
    }
    jdbcTemplateCallback.doInJdbcTemplate(template, sql, sh);

    // Match
    String[] forenames = sh.getStrings();
    assertTrue("same length", forenames.length == results.length);
    for (int i = 0; i < forenames.length; i++) {
        assertTrue("Row " + i + " matches", forenames[i].equals(results[i]));
    }

    ctrlResultSet.verify();
    ctrlStatement.verify();
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

private GeneratedKey insertWithGeneratedKeyReturn(Object record, boolean useDeclaredOnly) {
    PreparedStatement st = null;
    boolean inTrans = inTransaction();
    String command = null;// w w  w .  j  ava 2s  .c o m
    int batchCount = 0;
    GeneratedKey gk = null;
    if (!inTrans)
        startTransaction();
    try {
        Class objClass = record.getClass();
        String schema = getEntitySchema(objClass);
        Boolean isCamelCased = useCamelCase(objClass);
        HashMap<Method, String> fieldMapping = getFieldMapping(objClass, GET, isCamelCased, useDeclaredOnly);
        String idFieldName = getIdFieldName(fieldMapping);
        HashMap<Integer, Method> indexMapping = new HashMap();
        String tableName = getTableName(objClass);
        if (tableName == null)
            tableName = getDbName(isCamelCased, objClass.getSimpleName(), null);
        command = getInsertCommand(tableName, schema, fieldMapping, indexMapping);
        if (idFieldName != null) {
            st = conn.prepareStatement(command, new String[] { idFieldName });
        } else {
            st = conn.prepareStatement(command);
        }
        for (int index : indexMapping.keySet()) {
            Object value = indexMapping.get(index).invoke(record, null);
            if (value instanceof java.util.Date) {
                value = new java.sql.Date(((java.util.Date) value).getTime());
            }
            st.setObject((Integer) index, value);
        }
        st.execute();
        ResultSet rs = st.getGeneratedKeys();
        if (rs.next()) {
            gk = new GeneratedKey(idFieldName, rs.getObject(1));
        }
        if (!inTrans)
            commitTransaction();
        return gk;
    } catch (Exception ex) {
        ex.printStackTrace();
        if (!inTrans)
            rollbackTransaction();
        throw new DataQueryException(command, "insertWithGeneratedKeyReturn", ex);
    } finally {
        if (st != null) {
            try {
                st.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.stgmastek.core.purge.PurgeBatchDetails.java

/**
 * The method for purge batch details//from ww w  .  j  a va2 s. com
 * <p>
 * Fetches configuration details like no of days to retain, installation
 * name, insert script back up directory from configuration as in the
 * CONFIGURATION table.</br> Executes the SQL to get the batch number list
 * for given no of days to retain. Creates the output file as
 * JBeam<indtallation name>batchno.sql for each batch no in BACKUP_DIR</br>
 * Verifies the output file in BACKUP_DIR before creating and if exists then
 * deletes it.</br>
 * </p>
 * Insert scripts of tables in the following order <li>BATCH</li><li>
 * PROGRESS_LEVEL</li><li>LOG</li><li>SYSTEM_INFO</li> <li>INSTRUCTION_LOG</li>
 * <li>INSTRUCTION_PARAMETERS</li></br></br>
 * <p>
 * Deletes the details from table in the following order
 * </p>
 * <li>SYSTEM_INFO</li><li>LOG</li><li>INSTRUCTION_PARAMETERS</li><li>
 * INSTRUCTION_LOG</li> <li>PROGRESS_LEVEL</li><li>BATCH</li>
 * 
 * @see ProcessRequestServicer#processRequest()
 * @return true if insert and delete successful, false otherwise
 * @throws SQLException
 *             Any exception occurred during the execution of the SQL
 */

public boolean processRequest() throws CProcessRequestEngineException {
    try {
        out = getResponseWriter();
    } catch (IOException e1) {
        throw new CProcessRequestEngineException(e1.getMessage(), e1);
    }
    ResultSet rs = null;
    String strInstallation = null;
    String strOutputDirectory = null;
    PreparedStatement psSelect = null;
    ArrayList<String> batchNoList = new ArrayList<String>();
    Integer noOfDaysToRetain = null;
    Boolean returnValue = false;
    Connection con = null;
    try {
        con = getDataSourceFactory().getDataSource(Constants.POOL_NAMES.BATCH.name()).getConnection();

        psSelect = con.prepareStatement(
                "select VALUE from configuration where code1= 'CORE' and code2='PURGE' and code3='RETAIN_DAYS'");
        rs = psSelect.executeQuery();
        if (rs.next()) {
            noOfDaysToRetain = Integer.valueOf(rs.getString(1));
        }
        rs.close();
        psSelect.close();
        if (noOfDaysToRetain == null) {
            logger.fatal("Number of Days must be configured. Unable to proceed.");
            return false;
        }
        if (noOfDaysToRetain <= 0) {
            logger.fatal("Number of Days to be retained cannot be <= zero.");
            return false;
        }

        psSelect = con.prepareStatement(
                "select value from configuration where code1= 'CORE' and code2='INSTALLATION' and code3='CODE'");
        rs = psSelect.executeQuery();
        if (rs.next()) {
            strInstallation = rs.getString(1);
        } else {
            strInstallation = "NotConfigured";
        }
        rs.close();
        psSelect.close();

        psSelect = con.prepareStatement(
                "select value from configuration where code1='CORE' and code2 ='PURGE' and code3 = 'BACKUP_DIR'");
        rs = psSelect.executeQuery();
        if (rs.next()) {
            strOutputDirectory = rs.getString(1);
        }
        rs.close();
        psSelect.close();
        Day day = new Day(JBeamTimeFactory.getInstance().getCurrentTimestamp(con));
        day.advance(noOfDaysToRetain * -1);
        resolveDirectory(new File(strOutputDirectory));
        psSelect = con
                .prepareStatement("select batch_no from batch where exec_start_time < ? order by batch_no");
        psSelect.setObject(1, day.getTimestamp());
        rs = psSelect.executeQuery();
        while (rs.next()) {
            batchNoList.add(rs.getString(1));
        }
        out.println("Purging BatchNo List--" + batchNoList);
        rs.close();

        if (insertPurgeScripts(con, batchNoList, strOutputDirectory, strInstallation)) {
            deleteBatchDetails(con, batchNoList);
            returnValue = true;
        }
    } catch (SQLException sqle1) {
        logger.error("SQLException:", sqle1);
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (psSelect != null) {
                psSelect.close();
            }
            if (con != null) {
                con.close();
            }
            noOfDaysToRetain = null;
            strInstallation = null;
            batchNoList = null;
        } catch (SQLException e) {
            logger.error("Exception in finally:", e);
        }
    }
    return returnValue;
}

From source file:org.brucalipto.sqlutil.SQLManager.java

protected int executeSimpleQuery(final String preparedStatement, final SQLParameter[] params) {
    final SQLParameter[] parameters;
    if (params == null) {
        parameters = new SQLParameter[0];
        log.debug("Going to execute a query without parameters.");
    } else {//  w  w w. j  ava2 s  .c om
        parameters = (SQLParameter[]) params.clone();
    }
    Connection dbConn = null;
    PreparedStatement pstmt = null;
    try {
        if (this.dataSource != null) {
            dbConn = this.dataSource.getConnection();
        } else {
            dbConn = this.connection;
        }
        pstmt = dbConn.prepareStatement(preparedStatement);
        for (int i = 0; i < parameters.length; i++) {
            final SQLParameter param = parameters[i];
            log.debug((i + 1) + ") Going to add parameter " + param);
            final int sqlType = param.getSqlType();
            final Object paramValue = param.getValue();
            if (paramValue == null) {
                pstmt.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                pstmt.setString(i + 1, (String) paramValue);
                break;
            case Types.INTEGER:
                if (paramValue instanceof Integer) {
                    pstmt.setInt(i + 1, ((Integer) paramValue).intValue());
                } else if (paramValue instanceof Long) {
                    pstmt.setLong(i + 1, ((Long) paramValue).longValue());
                }
                break;
            case Types.DATE:
                pstmt.setDate(i + 1, (Date) paramValue);
                break;
            case Types.BOOLEAN:
                pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue());
                break;
            case Types.CHAR:
                pstmt.setString(i + 1, ((Character) paramValue).toString());
                break;
            case Types.DOUBLE:
                pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue());
                break;
            case Types.FLOAT:
                pstmt.setFloat(i + 1, ((Float) paramValue).floatValue());
                break;
            case Types.TIMESTAMP:
                pstmt.setTimestamp(i + 1, (Timestamp) paramValue);
                break;
            default:
                pstmt.setObject(i + 1, paramValue);
                break;
            }
        }

        int result = pstmt.executeUpdate();
        log.debug("Prepared statement '" + preparedStatement + "' correctly executed (" + result + ")");
        return result;
    } catch (SQLException e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } catch (Exception e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } finally {
        closeResources(pstmt, dbConn);
    }

    return -1;
}

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

private void runDml(DML dmlType, List records, boolean useDeclaredOnly) {
    PreparedStatement st = null;
    boolean inTrans = inTransaction();
    int batchCount = 0;
    String command = null;/*  w w w.jav  a  2  s . c  o  m*/
    if (!inTrans)
        startTransaction();
    try {
        Object obj = records.get(0);
        Class objClass = obj.getClass();
        String schema = getEntitySchema(objClass);
        Boolean isCamelCased = useCamelCase(objClass);
        HashMap<Method, String> fieldMapping = getFieldMapping(objClass, GET, isCamelCased, useDeclaredOnly);
        HashMap<Integer, Method> indexMapping = new HashMap();
        String tableName = getTableName(objClass);
        if (tableName == null)
            tableName = getDbName(isCamelCased, objClass.getSimpleName(), null);

        if (dmlType == DML.UPDATE)
            command = getUpdateCommand(tableName, schema, fieldMapping, indexMapping);
        else if (dmlType == DML.INSERT)
            command = getInsertCommand(tableName, schema, fieldMapping, indexMapping);
        else
            command = getDeleteCommand(tableName, schema, fieldMapping, indexMapping);

        st = conn.prepareStatement(command);

        for (Object record : records) {
            for (int index : indexMapping.keySet()) {
                Object value = indexMapping.get(index).invoke(record, null);
                if (value instanceof java.util.Date) {
                    value = new java.sql.Date(((java.util.Date) value).getTime());
                }
                st.setObject((Integer) index, value);
            }

            if (useBatch == true)
                st.addBatch();
            else
                st.executeUpdate();

            if (useBatch == true && ++batchCount % batchSize == 0) {
                st.executeBatch();
            }
        }
        if (useBatch == true)
            st.executeBatch(); //flush out remaining records
        if (!inTrans)
            commitTransaction();
    } catch (Exception ex) {
        ex.printStackTrace();
        if (!inTrans)
            rollbackTransaction();
        throw new NativeQueryException(command, "runDml", ex);
    } finally {
        if (st != null) {
            try {
                st.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkLoader.java

/**
 * Load the tuples for the given table name
 * @param tableName/*from   w ww.j a va  2s  .com*/
 */
protected void generateTableData(String tableName) throws SQLException {
    LOG.info("*** START " + tableName);
    final AbstractTableGenerator generator = this.generators.get(tableName);
    assert (generator != null);

    // Generate Data
    final Table catalog_tbl = benchmark.getCatalog().getTable(tableName);
    assert (catalog_tbl != null) : tableName;
    final List<Object[]> volt_table = generator.getVoltTable();
    final String sql = SQLUtil.getInsertSQL(catalog_tbl);
    final PreparedStatement stmt = conn.prepareStatement(sql);
    final int types[] = catalog_tbl.getColumnTypes();

    while (generator.hasMore()) {
        generator.generateBatch();

        //            StringBuilder sb = new StringBuilder();
        //            if (tableName.equalsIgnoreCase("USER_FEEDBACK")) { //  || tableName.equalsIgnoreCase("USER_ATTRIBUTES")) {
        //                sb.append(tableName + "\n");
        //                for (int i = 0; i < volt_table.size(); i++) {
        //                    sb.append(String.format("[%03d] %s\n", i, StringUtil.abbrv(Arrays.toString(volt_table.get(i)), 100)));
        //                }
        //                LOG.info(sb.toString() + "\n");
        //            }

        for (Object row[] : volt_table) {
            for (int i = 0; i < row.length; i++) {
                if (row[i] != null) {
                    stmt.setObject(i + 1, row[i]);
                } else {
                    stmt.setNull(i + 1, types[i]);
                }
            } // FOR
            stmt.addBatch();
        } // FOR
        try {
            stmt.executeBatch();
            conn.commit();
            stmt.clearBatch();
        } catch (SQLException ex) {
            if (ex.getNextException() != null)
                ex = ex.getNextException();
            LOG.warn(tableName + " - " + ex.getMessage());
            throw ex;
            // SKIP
        }

        this.tableSizes.put(tableName, volt_table.size());

        // Release anything to the sub-generators if we have it
        // We have to do this to ensure that all of the parent tuples get
        // insert first for foreign-key relationships
        generator.releaseHoldsToSubTableGenerators();
    } // WHILE
    stmt.close();

    // Mark as finished
    if (this.fail == false) {
        generator.markAsFinished();
        synchronized (this) {
            this.finished.add(tableName);
            LOG.info(String.format("*** FINISH %s - %d tuples - [%d / %d]", tableName,
                    this.tableSizes.get(tableName), this.finished.size(), this.generators.size()));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Remaining Tables: "
                        + CollectionUtils.subtract(this.generators.keySet(), this.finished));
            }
        } // SYNCH
    }
}

From source file:org.brucalipto.sqlutil.SQLManager.java

/**
 * Method useful for SQL SELECT// w  w w.  java2  s . c  o  m
 * @param preparedStatement The prepared statement to execute
 * @param params List of {@link SQLParameter} to use to complete the prepared statement
 * @param outputSQLType A java.sql.Types type of return value
 * @return The {@link SPParameter} containing the returned value
 */
public SQLParameter simpleSelect(final String preparedStatement, SQLParameter[] params,
        final int outputSQLType) {
    final SQLParameter[] parameters;
    if (params == null) {
        parameters = new SQLParameter[0];
        log.debug("Going to execute a query without parameters.");
    } else {
        parameters = (SQLParameter[]) params.clone();
    }
    Connection dbConn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        if (this.dataSource != null) {
            dbConn = this.dataSource.getConnection();
        } else {
            dbConn = this.connection;
        }
        pstmt = dbConn.prepareStatement(preparedStatement);
        for (int i = 0; i < parameters.length; i++) {
            final SQLParameter param = parameters[i];
            log.debug((i + 1) + ") Going to add parameter " + param);
            final int sqlType = param.getSqlType();
            final Object paramValue = param.getValue();
            if (paramValue == null) {
                pstmt.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                pstmt.setString(i + 1, (String) paramValue);
                break;
            case Types.INTEGER:
                if (paramValue instanceof Integer) {
                    pstmt.setInt(i + 1, ((Integer) paramValue).intValue());
                } else if (paramValue instanceof Long) {
                    pstmt.setLong(i + 1, ((Long) paramValue).longValue());
                }
                break;
            case Types.DATE:
                pstmt.setDate(i + 1, (Date) paramValue);
                break;
            case Types.BOOLEAN:
                pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue());
                break;
            case Types.CHAR:
                pstmt.setString(i + 1, ((Character) paramValue).toString());
                break;
            case Types.DOUBLE:
                pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue());
                break;
            case Types.FLOAT:
                pstmt.setFloat(i + 1, ((Float) paramValue).floatValue());
                break;
            case Types.TIMESTAMP:
                pstmt.setTimestamp(i + 1, (Timestamp) paramValue);
                break;
            default:
                pstmt.setObject(i + 1, paramValue);
                break;
            }
        }

        rs = pstmt.executeQuery();
        log.debug("Prepared statement '" + preparedStatement + "' succesfully executed!");
        while (rs.next()) {
            return new SQLParameter(outputSQLType, (Serializable) rs.getObject(1));
        }
        log.info("Prepared statement '" + preparedStatement + "' returned '0' rows");
    } catch (SQLException e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } catch (Exception e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } finally {
        closeResources(rs, pstmt, dbConn);
    }

    return new SQLParameter(outputSQLType, null);
}

From source file:org.brucalipto.sqlutil.SQLManager.java

/**
 * Method useful for SQL SELECT/*from  w  w w  .  j av  a  2 s.  c o  m*/
 * @param preparedStatement The prepared statement to execute
 * @param parameters List of {@link SQLParameter} to use to complete the prepared statement
 * @return Returns a RowSetDynaClass containing returned rows
 * @throws SQLException 
 */
public RowSetDynaClass dynaSelect(final String preparedStatement, final SQLParameter[] params)
        throws SQLException {
    final long elapsedTime = System.currentTimeMillis();
    SQLParameter[] parameters;
    if (params == null) {
        parameters = new SQLParameter[0];
        log.debug("Going to execute a query without parameters.");
    } else {
        parameters = (SQLParameter[]) params.clone();
    }
    Connection dbConn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        if (this.dataSource != null) {
            dbConn = this.dataSource.getConnection();
        } else {
            dbConn = this.connection;
        }
        pstmt = dbConn.prepareStatement(preparedStatement);
        for (int i = 0; i < parameters.length; i++) {
            final SQLParameter param = parameters[i];
            log.debug((i + 1) + ") Going to add parameter " + param);
            final int sqlType = param.getSqlType();
            final Object paramValue = param.getValue();
            if (paramValue == null) {
                pstmt.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                pstmt.setString(i + 1, (String) paramValue);
                break;
            case Types.INTEGER:
                if (paramValue instanceof Integer) {
                    pstmt.setInt(i + 1, ((Integer) paramValue).intValue());
                } else if (paramValue instanceof Long) {
                    pstmt.setLong(i + 1, ((Long) paramValue).longValue());
                }
                break;
            case Types.DATE:
                pstmt.setDate(i + 1, (Date) paramValue);
                break;
            case Types.BOOLEAN:
                pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue());
                break;
            case Types.CHAR:
                pstmt.setString(i + 1, ((Character) paramValue).toString());
                break;
            case Types.DOUBLE:
                pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue());
                break;
            case Types.FLOAT:
                pstmt.setFloat(i + 1, ((Float) paramValue).floatValue());
                break;
            case Types.TIMESTAMP:
                pstmt.setTimestamp(i + 1, (Timestamp) paramValue);
                break;
            default:
                pstmt.setObject(i + 1, paramValue);
                break;
            }
        }

        rs = pstmt.executeQuery();
        RowSetDynaClass rowSetDynaClass = new RowSetDynaClass(rs, false);
        if (log.isDebugEnabled()) {
            log.debug("Prepared statement '" + preparedStatement + "' returned '"
                    + rowSetDynaClass.getRows().size() + "' rows in '"
                    + (System.currentTimeMillis() - elapsedTime) + "' millis with following properties:");
            DynaProperty[] properties = rowSetDynaClass.getDynaProperties();
            for (int i = 0; i < properties.length; i++) {
                log.debug("Name: '" + properties[i].getName() + "'; Type: '" + properties[i].getType().getName()
                        + "'");
            }
        }
        return rowSetDynaClass;
    } catch (SQLException e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
        throw e;
    } finally {
        closeResources(rs, pstmt, dbConn);
    }
}

From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

/**
 * bind the variables to the prepared statement
 * /*  w w  w.ja  v a2 s  . co  m*/
 * @param type
 * @param mapInfo
 * @param ps
 * @param annoId
 * @param anno
 * @throws SQLException
 */
private void saveAnnoBindVariables(final Type type, final AnnoMappingInfo mapInfo, PreparedStatement ps,
        int annoId, FeatureStructure anno, final BiMap<Annotation, Integer> mapAnnoToId) throws SQLException {
    // set anno_base_id
    int argIdx = 1;
    ps.setInt(argIdx++, annoId);
    if (mapInfo.getCoveredTextColumn() != null) {
        String trunc = null;
        if (anno instanceof Annotation) {
            trunc = truncateString(((Annotation) anno).getCoveredText(),
                    mapInfo.getCoveredTextColumn().getSize());
        }
        ps.setString(argIdx++, trunc);
    }
    if (!Strings.isNullOrEmpty(mapInfo.getUimaTypeIdColumnName())) {
        ps.setInt(argIdx++, mapInfo.getUimaTypeId());
    }
    // iterate over fields
    for (Map.Entry<String, ColumnMappingInfo> fieldEntry : mapInfo.getMapField().entrySet()) {
        ColumnMappingInfo fieldMapInfo = fieldEntry.getValue();
        String fieldName = fieldMapInfo.getAnnoFieldName();
        Feature feat = type.getFeatureByBaseName(fieldName);
        if (fieldMapInfo.getConverter() != null) {
            try {
                String prop = anno.getFeatureValueAsString(feat);
                ps.setObject(argIdx, fieldMapInfo.getConverter().convert(fieldMapInfo.getTargetType(), prop));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (!feat.getRange().isPrimitive()) {
            // feature is a structure/annotation
            FeatureStructure fs = anno.getFeatureValue(feat);
            if (fs == null) {
                // feature is null - set the column to null
                ps.setNull(argIdx, fieldMapInfo.getSqlType());
            } else {
                if (fieldMapInfo.getJxpath() != null) {
                    // jxpath to pull out feature attribute
                    Object o = this.extractFeature(fieldMapInfo.getJxpath(), fs);
                    if (o == null) {
                        // extracted value null - set column to null
                        ps.setNull(argIdx, fieldMapInfo.getSqlType());
                    } else if (o instanceof String) {
                        // string - truncate as needed
                        String trunc = truncateString((String) o, fieldMapInfo.getSize());
                        ps.setString(argIdx, trunc);
                    } else {
                        // set value
                        ps.setObject(argIdx, o);
                    }
                } else {
                    // reference to another annotation - get the other
                    // anno's id
                    Integer refAnnoId = null;
                    if (fs instanceof Annotation) {
                        refAnnoId = mapAnnoToId.get(fs);
                    }
                    if (refAnnoId != null) {
                        ps.setInt(argIdx, refAnnoId);
                    } else {
                        ps.setNull(argIdx, Types.INTEGER);
                    }
                }
            }
        } else {
            if ("uima.cas.Integer".equals(feat.getRange().getName())) {
                ps.setInt(argIdx, anno.getIntValue(feat));
            } else if ("uima.cas.Short".equals(feat.getRange().getName())) {
                ps.setShort(argIdx, anno.getShortValue(feat));
            } else if ("uima.cas.Long".equals(feat.getRange().getName())) {
                ps.setLong(argIdx, anno.getLongValue(feat));
            } else if ("uima.cas.Float".equals(feat.getRange().getName())) {
                ps.setFloat(argIdx, anno.getFloatValue(feat));
            } else if ("uima.cas.Double".equals(feat.getRange().getName())) {
                ps.setDouble(argIdx, anno.getDoubleValue(feat));
            } else if ("uima.cas.Byte".equals(feat.getRange().getName())) {
                ps.setByte(argIdx, anno.getByteValue(feat));
            } else if ("uima.cas.Boolean".equals(feat.getRange().getName())) {
                ps.setBoolean(argIdx, anno.getBooleanValue(feat));
            } else if ("uima.cas.String".equals(feat.getRange().getName())) {
                String trunc = truncateString(anno.getStringValue(feat), fieldMapInfo.getSize());
                ps.setString(argIdx, trunc);
            }
        }
        argIdx++;
    }
}