Example usage for java.sql PreparedStatement setClob

List of usage examples for java.sql PreparedStatement setClob

Introduction

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

Prototype

void setClob(int parameterIndex, Reader reader) throws SQLException;

Source Link

Document

Sets the designated parameter to a Reader object.

Usage

From source file:org.batoo.jpa.jdbc.dbutils.QueryRunner.java

/**
 * Fill the <code>PreparedStatement</code> replacement parameters with the given objects.
 * /*w w  w. j  a  va 2  s  .  c o m*/
 * @param statement
 *            PreparedStatement to fill
 * @param params
 *            Query replacement parameters; <code>null</code> is a valid value to pass in.
 * @throws SQLException
 *             if a database access error occurs
 */
private void fillStatement(PreparedStatement statement, Object... params) throws SQLException {
    // use local variable for performance
    boolean pmdKnownBroken = this.pmdKnownBroken;
    ParameterMetaData pmd = this.pmd;
    final boolean hasLob = this.hasLob;

    if (pmdKnownBroken) {
        ((PreparedStatementProxy) statement).setParamCount(params.length);
    } else {
        ((PreparedStatementProxy) statement).setParamCount(-1);
    }

    // if the jdbc adaptor wants to modify the parameters we let it do it its own way
    final JdbcAdaptor jdbcAdaptor = this.jdbcAdaptor;
    if ((jdbcAdaptor != null) && jdbcAdaptor.modifiesParameters()) {
        pmd = this.pmd = statement.getParameterMetaData();

        jdbcAdaptor.modifyParameters(pmd, params);
    }

    for (int i = 0; i < params.length; i++) {
        final Object param = params[i];
        if ((param != null) && (param != Void.TYPE)) {
            if (hasLob && (param instanceof Clob)) {
                if (this.jdbcAdaptor instanceof OracleAdaptor) {
                    statement.setCharacterStream(i + 1, ((Clob) param).getCharacterStream());
                } else {
                    statement.setClob(i + 1, (Clob) param);
                }
            } else if (hasLob && (param instanceof Blob)) {
                if (this.jdbcAdaptor instanceof OracleAdaptor) {
                    statement.setBinaryStream(i + 1, ((Blob) param).getBinaryStream());
                } else {
                    statement.setBlob(i + 1, (Blob) param);
                }
            } else {
                statement.setObject(i + 1, param);
            }
        } else {
            if (!pmdKnownBroken && (pmd == null)) {
                pmd = this.pmd = statement.getParameterMetaData();
            }

            // VARCHAR works with many drivers regardless of the actual column type.
            // Oddly, NULL and OTHER don't work with Oracle's drivers.
            int sqlType = Types.VARCHAR;
            if (!pmdKnownBroken) {
                try {
                    sqlType = pmd.getParameterType(i + 1);
                } catch (final SQLException e) {
                    pmdKnownBroken = this.pmdKnownBroken = true;
                }
            }
            if (param != Void.TYPE) {
                statement.setNull(i + 1, sqlType);
            }
        }
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java

@Override
protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps,
        final EntityEntry entry, boolean useAutoInc) throws DatabaseEngineException {

    int i = 1;/*ww  w . j  a  va2 s .  c  om*/
    for (DbColumn column : entity.getColumns()) {
        if (column.isAutoInc() && useAutoInc) {
            continue;
        }

        try {
            final Object val;
            if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) {
                val = column.getDefaultValue().getConstant();
            } else {
                val = entry.get(column.getName());
            }
            switch (column.getDbColumnType()) {
            case BLOB:
                ps.setBytes(i, objectToArray(val));

                break;

            case CLOB:
                if (val == null) {
                    ps.setNull(i, Types.CLOB);
                    break;
                }

                if (val instanceof String) {
                    StringReader sr = new StringReader((String) val);
                    ps.setClob(i, sr);
                } else {
                    throw new DatabaseEngineException("Cannot convert " + val.getClass().getSimpleName()
                            + " to String. CLOB columns only accept Strings.");
                }
                break;
            case BOOLEAN:
                Boolean b = (Boolean) val;
                if (b == null) {
                    ps.setObject(i, null);
                } else if (b) {
                    ps.setObject(i, 1);
                } else {
                    ps.setObject(i, 0);
                }

                break;
            default:
                ps.setObject(i, val);
            }
        } catch (Exception ex) {
            throw new DatabaseEngineException("Error while mapping variables to database", ex);
        }

        i++;
    }

    return i - 1;
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.MySqlEngine.java

@Override
protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps,
        final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException {

    int i = 1;//www.ja  v a  2  s  .  c  om
    for (DbColumn column : entity.getColumns()) {
        if (column.isAutoInc() && useAutoInc) {
            continue;
        }

        try {
            final Object val;
            if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) {
                val = column.getDefaultValue().getConstant();
            } else {
                val = entry.get(column.getName());
            }

            switch (column.getDbColumnType()) {
            case BLOB:
                ps.setBytes(i, objectToArray(val));

                break;
            case CLOB:
                if (val == null) {
                    ps.setNull(i, Types.CLOB);
                    break;
                }

                if (val instanceof String) {
                    StringReader sr = new StringReader((String) val);
                    ps.setClob(i, sr);
                } else {
                    throw new DatabaseEngineException("Cannot convert " + val.getClass().getSimpleName()
                            + " to String. CLOB columns only accept Strings.");
                }
                break;
            case BOOLEAN:
                Boolean b = (Boolean) val;
                if (b == null) {
                    ps.setObject(i, null);
                } else if (b) {
                    ps.setObject(i, 1);
                } else {
                    ps.setObject(i, 0);
                }

                break;
            default:
                ps.setObject(i, val);
            }
        } catch (Exception ex) {
            throw new DatabaseEngineException("Error while mapping variable s to database", ex);
        }

        i++;
    }

    return i - 1;
}

From source file:com.oracle.tutorial.jdbc.RSSFeedsTable.java

public void addRSSFeed(String fileName) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerConfigurationException, TransformerException, SQLException {
    // Parse the document and retrieve the name of the RSS feed

    String titleString = null;//from  www  .  j ava2s.co m

    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    Node titleElement = (Node) xPath.evaluate("/rss/channel/title[1]", doc, XPathConstants.NODE);

    if (titleElement == null) {
        System.out.println("Unable to retrieve title element");
        return;
    } else {
        titleString = titleElement.getTextContent().trim().toLowerCase().replaceAll("\\s+", "_");
        System.out.println("title element: [" + titleString + "]");
    }

    System.out.println(JDBCTutorialUtilities.convertDocumentToString(doc));

    PreparedStatement insertRow = null;
    SQLXML rssData = null;

    System.out.println("Current DBMS: " + this.dbms);

    try {
        if (this.dbms.equals("mysql")) {
            // For databases that support the SQLXML data type, this creates a
            // SQLXML object from org.w3c.dom.Document.

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values" + " (?, ?)";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);

            System.out.println("Creating SQLXML object with MySQL");
            rssData = con.createSQLXML();
            System.out.println("Creating DOMResult object");
            DOMResult dom = (DOMResult) rssData.setResult(DOMResult.class);
            dom.setNode(doc);

            insertRow.setSQLXML(2, rssData);
            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

        else if (this.dbms.equals("derby")) {

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values"
                    + " (?, xmlparse(document cast (? as clob) preserve whitespace))";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);
            String convertedDoc = JDBCTutorialUtilities.convertDocumentToString(doc);
            insertRow.setClob(2, new StringReader(convertedDoc));

            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (Exception ex) {
        System.out.println("Another exception caught:");
        ex.printStackTrace();
    }

    finally {
        if (insertRow != null) {
            insertRow.close();
        }
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.impl.OracleEngine.java

@Override
protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps,
        final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException {
    int i = 1;/*from   www  . j  a v  a2s. c  o m*/
    for (DbColumn column : entity.getColumns()) {
        if (column.isAutoInc() && useAutoInc) {
            continue;
        }

        try {
            final Object val;
            if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) {
                val = column.getDefaultValue().getConstant();
            } else {
                val = entry.get(column.getName());
            }
            switch (column.getDbColumnType()) {
            case BLOB:
                ps.setBytes(i, objectToArray(val));

                break;
            case CLOB:
                if (val == null) {
                    ps.setNull(i, Types.CLOB);
                    break;
                }

                if (val instanceof String) {
                    StringReader sr = new StringReader((String) val);
                    ps.setClob(i, sr);
                } else {
                    throw new DatabaseEngineException("Cannot convert " + val.getClass().getSimpleName()
                            + " to String. CLOB columns only accept Strings.");
                }
                break;
            case BOOLEAN:
                Boolean b = (Boolean) val;
                if (b == null) {
                    ps.setObject(i, null);
                } else if (b) {
                    ps.setObject(i, "1");
                } else {
                    ps.setObject(i, "0");
                }

                break;
            default:
                ps.setObject(i, ensureNoUnderflow(val));
            }
        } catch (Exception ex) {
            throw new DatabaseEngineException("Error while mapping variables to database", ex);
        }

        i++;
    }

    return i - 1;
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

@Override
public synchronized boolean updateDemandStats(DemandReport<NodeIDType> report) {
    JSONObject update = report.getStats();
    JSONObject historic = getDemandStatsJSON(report.getServiceName());
    JSONObject combined = null;/*from   www  .j a  v a 2  s .com*/
    String insertCmd = "insert into " + getDemandTable() + " (" + Columns.DEMAND_PROFILE.toString() + ", "
            + Columns.SERVICE_NAME.toString() + " ) values (?,?)";
    String updateCmd = "update " + getDemandTable() + " set " + Columns.DEMAND_PROFILE.toString() + "=? where "
            + Columns.SERVICE_NAME.toString() + "=?";
    String cmd = historic != null ? updateCmd : insertCmd;
    combined = update;
    if (historic != null && shouldCombineStats())
        combined = combineStats(historic, update);

    PreparedStatement insertCP = null;
    Connection conn = null;
    try {
        conn = this.getDefaultConn();
        insertCP = conn.prepareStatement(cmd);
        if (DEMAND_PROFILE_CLOB_OPTION)
            insertCP.setClob(1, new StringReader(combined.toString()));
        else
            insertCP.setString(1, combined.toString());
        insertCP.setString(2, report.getServiceName());
        insertCP.executeUpdate();
        // conn.commit();
    } catch (SQLException sqle) {
        log.severe("SQLException while updating stats using " + cmd);
        sqle.printStackTrace();
    } finally {
        cleanup(insertCP);
        cleanup(conn);
    }
    return true;
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private void putReconfigurationRecordDB(ReconfigurationRecord<NodeIDType> rcRecord, String rcGroupName) {
    ReconfigurationRecord<NodeIDType> prev = this.getReconfigurationRecordDB(rcRecord.getName());
    String insertCmd = "insert into " + getRCRecordTable() + " (" + Columns.RC_GROUP_NAME.toString() + ", "
            + Columns.STRINGIFIED_RECORD.toString() + ", " + Columns.SERVICE_NAME.toString()
            + " ) values (?,?,?)";
    String updateCmd = "update " + getRCRecordTable() + " set " + Columns.RC_GROUP_NAME.toString() + "=?, "
            + Columns.STRINGIFIED_RECORD.toString() + "=? where " + Columns.SERVICE_NAME.toString() + "=?";
    String cmd = prev != null ? updateCmd : insertCmd;

    rcRecord.setRCGroupName(rcGroupName);

    PreparedStatement insertCP = null;
    Connection conn = null;//from w ww. jav  a 2 s  .  co m
    try {
        conn = this.getDefaultConn();
        insertCP = conn.prepareStatement(cmd);
        insertCP.setString(1, rcGroupName);
        if (RC_RECORD_CLOB_OPTION)
            insertCP.setClob(2, new StringReader(rcRecord.toString()));
        else
            insertCP.setString(2, rcRecord.toString());
        insertCP.setString(3, rcRecord.getName());
        insertCP.executeUpdate();
        // conn.commit();
    } catch (SQLException sqle) {
        log.severe("SQLException while inserting RC record using " + cmd);
        sqle.printStackTrace();
    } finally {
        cleanup(insertCP);
        cleanup(conn);
    }
    // printRCTable();
    log.log(Level.FINE, "{0} put {1} into RC group {2}",
            new Object[] { this, rcRecord.getSummary(), rcGroupName });
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column/*  w  w  w . j ava2 s  . c om*/
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

From source file:cz.lbenda.dataman.db.RowDesc.java

@SuppressWarnings("ConstantConditions")
private <T> void putToPS(ColumnDesc columnDesc, T value, PreparedStatement ps, int position)
        throws SQLException {
    if (value == null) {
        ps.setObject(position, null);/*from  w w w .  j  a v a2s .  com*/
        return;
    }
    BinaryData bd = value instanceof BinaryData ? (BinaryData) value : null;
    switch (columnDesc.getDataType()) {
    case STRING:
        ps.setString(position, (String) value);
        break;
    case BOOLEAN:
        ps.setBoolean(position, (Boolean) value);
        break;
    case TIMESTAMP:
        ps.setTimestamp(position, (Timestamp) value);
        break;
    case DATE:
        ps.setDate(position, (Date) value);
        break;
    case TIME:
        ps.setTime(position, (Time) value);
        break;
    case BYTE:
        ps.setByte(position, (Byte) value);
        break;
    case SHORT:
        ps.setShort(position, (Short) value);
        break;
    case INTEGER:
        ps.setInt(position, (Integer) value);
        break;
    case LONG:
        ps.setLong(position, (Long) value);
        break;
    case FLOAT:
        ps.setFloat(position, (Float) value);
        break;
    case DOUBLE:
        ps.setDouble(position, (Double) value);
        break;
    case DECIMAL:
        ps.setBigDecimal(position, (BigDecimal) value);
        break;
    case UUID:
        ps.setBytes(position, AbstractHelper.uuidToByteArray((UUID) value));
        break;
    case ARRAY:
        throw new UnsupportedOperationException("The saving changes in ARRAY isn't supported.");
        // ps.setArray(position, (Array) value); break; // FIXME the value isn't in type java.sql.Array
    case BYTE_ARRAY:
        if (bd == null || bd.isNull()) {
            ps.setBytes(position, null);
        } else {
            try {
                ps.setBytes(position, IOUtils.toByteArray(bd.getInputStream()));
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
        break;
    case CLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.CLOB);
        } else {
            ps.setClob(position, bd.getReader());
        }
        break;
    case BLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.BLOB);
        } else {
            ps.setBlob(position, bd.getInputStream());
        }
        break;
    case OBJECT:
        ps.setObject(position, value);
    }
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private int buildStatementForInsertUpdate(Object obj, Set<String> ignoreFields,
        PreparedStatement preparedStatement, Connection connection)
        throws SQLException, WPBSerializerException {
    Class<? extends Object> kind = obj.getClass();
    Field[] fields = kind.getDeclaredFields();
    int fieldIndex = 0;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];//from ww  w  .  j  a v a  2s .c o  m
        field.setAccessible(true);
        boolean storeField = (field.getAnnotation(WPBAdminFieldKey.class) != null)
                || (field.getAnnotation(WPBAdminFieldStore.class) != null)
                || (field.getAnnotation(WPBAdminFieldTextStore.class) != null);
        if (storeField) {
            String fieldName = field.getName();
            if (ignoreFields != null && ignoreFields.contains(fieldName)) {
                continue;
            }
            fieldIndex = fieldIndex + 1;
            Object value = null;
            try {
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, kind);
                value = pd.getReadMethod().invoke(obj);
            } catch (Exception e) {
                throw new WPBSerializerException("Cannot get property value", e);
            }
            if (field.getType() == Long.class) {
                Long valueLong = (Long) value;
                if (valueLong != null) {
                    preparedStatement.setLong(fieldIndex, valueLong);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.BIGINT);
                }
            } else if (field.getType() == String.class) {

                String valueString = (String) value;
                if (field.getAnnotation(WPBAdminFieldStore.class) != null
                        || field.getAnnotation(WPBAdminFieldKey.class) != null) {
                    if (valueString != null) {
                        preparedStatement.setString(fieldIndex, valueString);
                    } else {
                        preparedStatement.setNull(fieldIndex, Types.VARCHAR);
                    }
                } else if (field.getAnnotation(WPBAdminFieldTextStore.class) != null) {
                    if (valueString != null) {
                        Clob clob = connection.createClob();
                        clob.setString(1, valueString);
                        preparedStatement.setClob(fieldIndex, clob);
                    } else {
                        preparedStatement.setNull(fieldIndex, Types.CLOB);
                    }
                }
            } else if (field.getType() == Integer.class) {
                Integer valueInt = (Integer) value;
                if (valueInt != null) {
                    preparedStatement.setInt(fieldIndex, valueInt);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.INTEGER);
                }
            } else if (field.getType() == Date.class) {
                Date date = (Date) value;
                if (date != null) {
                    java.sql.Timestamp sqlDate = new java.sql.Timestamp(date.getTime());
                    preparedStatement.setTimestamp(fieldIndex, sqlDate);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.DATE);
                }
            }
        }
    }
    return fieldIndex;
}