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:org.paxml.bean.excel.ReadExcelTag.java

protected PreparedStatement getPreparedStatement(Connection con) throws SQLException {

    PreparedStatement p = con.prepareStatement(query);
    if (queryParameter != null) {
        List list = new ArrayList();
        ReflectUtils.collect(queryParameter, list, true);
        for (int i = list.size() - 1; i >= 0; i--) {
            p.setObject(i, list.get(i));
        }//from w ww .  j av  a 2  s .  c  om
    }
    return p;
}

From source file:edu.ku.brc.specify.toycode.mexconabio.DataObjTableModel.java

/**
 * The Data members must be set to call this:
 *     numColumns/* ww w  .  j a  v a  2  s . co  m*/
 *     itemsList
 * 
 */
protected void fillModels() {
    final String sqlStr = buildSQL();

    TimeLogger tml = new TimeLogger("Fetching Rows");
    values = new Vector<Object[]>();

    if (StringUtils.isNotEmpty(sqlStr)) {
        log.debug(sqlStr);
        try {
            PreparedStatement pStmt = conn.prepareStatement(sqlStr);
            if (searchValue != null) {
                pStmt.setObject(1, searchValue);
            }
            log.debug(sqlStr + " [" + searchValue + "]");

            tml.restart("Query");
            ResultSet rs = pStmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();

            tml.restart("Loading");
            while (rs.next()) {
                Object[] row = new Object[numColumns];
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    Object obj = rs.getObject(i + 1);
                    row[i] = obj instanceof String ? obj.toString().trim() : obj;
                }
                rowInfoList.add(new DataObjTableModelRowInfo(rs.getInt(1), false, false));
                values.add(row);
                processColumns(row);
            }
            rs.close();
            pStmt.close();
            tml.end();

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    tml.restart("Step 2 - Addl Rows");
    addAdditionalRows(colDefItems, rowInfoList);

    tml.restart("Step 3");

    sameValues = new ArrayList<Boolean>(numColumns);
    hasDataList = new ArrayList<Boolean>(numColumns);
    for (int i = 0; i < numColumns; i++) {
        sameValues.add(true);
        hasDataList.add(false);
    }

    for (Object[] col : values) {
        for (int i = 0; i < numColumns; i++) {
            Object data = col[i];
            boolean hasData = data != null;

            if (hasData && !hasDataList.get(i)) {
                hasDataList.set(i, true);
                hasDataCols++;
            }
        }
    }

    tml.restart("Step  4 - adj cols");
    adjustHasDataColumns();

    tml.restart("Step  5 - Map");
    mapInx = new int[hasDataCols];
    int colInx = 0;
    //log.debug("-------------Has Data----------------------");
    for (int i = 0; i < numColumns; i++) {
        if (hasDataList.get(i)) {
            //log.debug(itemsList.get(i).getTitle());
            mapInx[colInx] = i;
            indexHash.put(i, colInx);
            //System.out.print("indexHash: "+i +" -> "+colInx);
            //log.debug("  mapInx:    "+colInx +" -> "+i);
            colInx++;
        }
    }

    tml.restart("Step  6 - same data");
    for (int i = 0; i < mapInx.length; i++) {
        colInx = mapInx[i];

        if (hasDataList.get(colInx)) {
            Object data = null;
            for (Object[] col : values) {
                Object newData = col[colInx];

                if (data == null) {
                    if (newData != null) {
                        data = newData;
                    }
                    continue;
                }

                if (newData != null && !data.equals(newData)) {
                    sameValues.set(colInx, false);
                    break;
                }
            }
        }
    }
    tml.end();
    /*
    log.debug("-----------Same------------------------");
    for (int i=0;i<mapInx.length;i++)
    {
        colInx = mapInx[i];
        if (sameValues.get(colInx))
        {
            log.debug(colInx + " " + itemsList.get(colInx).getTitle());
        }
    }*/

    items = new ArrayList<DBInfoBase>(colDefItems);
    doneFillingModels(values);
}

From source file:com.gs.obevo.db.impl.core.jdbc.JdbcHelper.java

public int[] batchUpdate(Connection conn, String sql, Object[][] argsArray) {
    PreparedStatement ps = null;
    try {//  w ww  . j a  v a 2  s  .c  o m
        this.jdbcHandler.preUpdate(conn, this);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing batch update on connection {}: {} with args: {}", displayConnection(conn), sql,
                    argsArray);
        }
        ps = conn.prepareStatement(sql);
        for (Object[] args : argsArray) {
            for (int j = 0; j < args.length; j++) {
                if (!parameterTypeEnabled || args[j] != null) {
                    ps.setObject(j + 1, args[j]);
                } else {
                    ps.setNull(j + 1, ps.getParameterMetaData().getParameterType(j + 1));
                }
            }
            ps.addBatch();
        }

        return ps.executeBatch();
    } catch (SQLException e) {
        LOG.error("Error during batch execution; will print out the full batch stack trace: ");
        this.logSqlBatchException(e, 0);
        throw new DataAccessException(e);
    } finally {
        DbUtils.closeQuietly(ps);
    }
}

From source file:info.naiv.lab.java.tool.sqlite.exporter.component.DataAccess.java

/**
 *
 * @param sourceTempl/*from www  .ja  v a2  s.c o  m*/
 * @param destTempl
 * @param info
 * @param valueHandler
 */
public void copy(final JdbcTemplate sourceTempl, JdbcTemplate destTempl, TableInfo info,
        final ValueHandler valueHandler) {

    final Query sq = selectTables.merge(info);

    Query q = insertSql.merge(info);
    final List<Field> fields = info.getFields();
    q.execute(destTempl, new PreparedStatementCallback<Void>() {

        @Override
        public Void doInPreparedStatement(final PreparedStatement ps) throws SQLException, DataAccessException {
            ps.getConnection().setAutoCommit(false);
            try {
                List<Integer> list = sq.query(sourceTempl, new RowMapper<Integer>() {

                    @Override
                    public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                        int col = 1;
                        for (Field field : fields) {
                            Object val = valueHandler.handleValue(field, rs);
                            ps.setObject(col, val);
                        }
                        ps.addBatch();
                        if (rowNum % BATCH_SIZE == 0) {
                            logger.info("execBatch: {}", rowNum);
                            ps.executeBatch();
                        }
                        return rowNum;
                    }
                });

                int total = list.size();
                logger.info("total Batch: {}", total);
                if (total % BATCH_SIZE != 0) {
                    ps.executeBatch();
                }
                ps.getConnection().commit();
            } catch (SQLException | RuntimeException e) {
                ps.getConnection().rollback();
                throw e;
            }
            return null;
        }
    });
}

From source file:org.ojbc.intermediaries.sn.dao.SubscriptionSearchQueryDAO.java

private PreparedStatementCreator buildPreparedInsertStatementCreator(final String sql, final Object[] params) {
    return new PreparedStatementCreator() {

        @Override/* www  .  jav a2 s .  c o  m*/
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
            int paramIndex = 1;
            for (Object param : params) {
                ps.setObject(paramIndex, param);
                paramIndex++;
            }
            return ps;
        }
    };
}

From source file:org.ala.dao.DocumentDAOImpl.java

/**
 * Save this document to the repository.
 * //  w  ww .ja v  a2 s. co m
 * @param doc
 */
public void save(final Document doc) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = null;
            if (doc.getId() < 0) {
                ps = conn.prepareStatement(INSERT);
            } else {
                ps = conn.prepareStatement(INSERT_WITH_ID);
                ps.setInt(8, doc.getId());
            }
            ps.setInt(1, doc.getInfoSourceId());
            ps.setString(2, doc.getUri());
            ps.setString(3, doc.getFilePath());
            ps.setString(4, doc.getMimeType());
            ps.setObject(5, doc.getParentDocumentId());

            if (doc.getCreated() != null) {
                ps.setObject(6, doc.getCreated());
            } else {
                ps.setObject(6, new Date());
            }

            if (doc.getModified() != null) {
                ps.setObject(7, doc.getModified());
            } else {
                ps.setObject(7, new Date());
            }
            return ps;
        }
    }, keyHolder);

    doc.setId(keyHolder.getKey().intValue());
}

From source file:de.iritgo.aktario.jdbc.JDBCManager.java

/**
 * Transfer all attribute values of a data object to the specified
 * prepared statement.//from  ww w .  j  a va  2 s .c o  m
 *
 * @param object The data object to transfer.
 * @param stmt The prepared statement.
 * @throws SQLException If an attribute could not be set.
 */
private void putAttributesToStatement(DataObject object, PreparedStatement stmt) throws SQLException {
    stmt.setLong(1, object.getUniqueId());

    int pos = 2;

    for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) {
        Map.Entry attribute = (Map.Entry) i.next();

        if (attribute.getValue() instanceof IObjectList) {
            continue;
        }

        stmt.setObject(pos++, attribute.getValue());
    }
}

From source file:org.etudes.jforum.dao.generic.GenericAttachmentDAO.java

private AttachmentExtension searchExtension(String paramName, Object paramValue) throws Exception {
    String sql = SystemGlobals.getSql("AttachmentModel.selectExtension");
    sql = sql.replaceAll("\\$field", paramName);

    PreparedStatement p = JForum.getConnection().prepareStatement(sql);
    p.setObject(1, paramValue);

    AttachmentExtension e = new AttachmentExtension();

    ResultSet rs = p.executeQuery();
    if (rs.next()) {
        e = this.getExtension(rs);
    } else {//from  www. j  a va2s .c o  m
        e.setUnknown(true);
    }

    rs.close();
    p.close();

    return e;
}

From source file:com.ineunet.knife.persist.Jdbc.java

/**
 * Column Name of Primary key must be 'id'.
 * /*w w  w.  j a  v a 2  s  .  c o m*/
 * @param sql
 * @param values
 * @return id
 */
public <X> Long createIncrement(final String sql, final Object... values) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(sql, new String[] { "id" });
            for (int i = 0; i < values.length; i++)
                ps.setObject(i + 1, values[i]);
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().longValue();
}

From source file:no.polaric.aprsdb.MyDBSession.java

/**
  * Encode and add a position to a PostGIS SQL statement.
  *//*from   w  w  w .  java2  s  . co m*/
private void setRef(PreparedStatement stmt, int index, Reference pos) throws SQLException {
    LatLng ll = pos.toLatLng();
    org.postgis.Point p = new org.postgis.Point(ll.getLng(), ll.getLat());
    p.setSrid(4326);
    stmt.setObject(index, new PGgeometry(p));
}