Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

In this page you can find the example usage for java.sql ResultSet getBytes.

Prototype

byte[] getBytes(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a byte array in the Java programming language.

Usage

From source file:org.traccar.database.QueryBuilder.java

private <T> void addProcessors(List<ResultSetProcessor<T>> processors, final Class<?> parameterType,
        final Method method, final String name) {

    if (parameterType.equals(boolean.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override/*from  www  . j av a2s.co m*/
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getBoolean(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(int.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getInt(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(long.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getLong(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(double.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getDouble(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(String.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getString(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(Date.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    Timestamp timestamp = resultSet.getTimestamp(name);
                    if (timestamp != null) {
                        method.invoke(object, new Date(timestamp.getTime()));
                    }
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(byte[].class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getBytes(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                String value = resultSet.getString(name);
                if (value != null && !value.isEmpty()) {
                    try {
                        method.invoke(object, Context.getObjectMapper().readValue(value, parameterType));
                    } catch (InvocationTargetException | IllegalAccessException | IOException error) {
                        Log.warning(error);
                    }
                }
            }
        });
    }
}

From source file:org.executequery.gui.resultset.ResultSetTableModel.java

public void createTable(ResultSet resultSet) {

    if (!isOpenAndValid(resultSet)) {

        clearData();//w  w w. j a  va2 s.co m
        return;
    }

    try {

        resetMetaData();
        ResultSetMetaData rsmd = resultSet.getMetaData();

        columnHeaders.clear();
        visibleColumnHeaders.clear();
        tableData.clear();

        int zeroBaseIndex = 0;
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {

            zeroBaseIndex = i - 1;

            columnHeaders.add(new ResultSetColumnHeader(zeroBaseIndex, rsmd.getColumnLabel(i),
                    rsmd.getColumnName(i), rsmd.getColumnType(i), rsmd.getColumnTypeName(i)));
        }

        int recordCount = 0;
        interrupted = false;

        if (holdMetaData) {

            setMetaDataVectors(rsmd);
        }

        List<RecordDataItem> rowData;
        long time = System.currentTimeMillis();
        while (resultSet.next()) {

            if (interrupted || Thread.interrupted()) {

                throw new InterruptedException();
            }

            recordCount++;
            rowData = new ArrayList<RecordDataItem>(count);

            for (int i = 1; i <= count; i++) {

                zeroBaseIndex = i - 1;

                ResultSetColumnHeader header = columnHeaders.get(zeroBaseIndex);
                RecordDataItem value = recordDataItemFactory.create(header);

                try {

                    int dataType = header.getDataType();
                    switch (dataType) {

                    // some drivers (informix for example)
                    // was noticed to return the hashcode from
                    // getObject for -1 data types (eg. longvarchar).
                    // force string for these - others stick with
                    // getObject() for default value formatting

                    case Types.CHAR:
                    case Types.VARCHAR:
                        value.setValue(resultSet.getString(i));
                        break;
                    case Types.DATE:
                        value.setValue(resultSet.getDate(i));
                        break;
                    case Types.TIME:
                        value.setValue(resultSet.getTime(i));
                        break;
                    case Types.TIMESTAMP:
                        value.setValue(resultSet.getTimestamp(i));
                        break;
                    case Types.LONGVARCHAR:
                    case Types.CLOB:
                        value.setValue(resultSet.getClob(i));
                        break;
                    case Types.LONGVARBINARY:
                    case Types.VARBINARY:
                    case Types.BINARY:
                        value.setValue(resultSet.getBytes(i));
                        break;
                    case Types.BLOB:
                        value.setValue(resultSet.getBlob(i));
                        break;
                    case Types.BIT:
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                    case Types.FLOAT:
                    case Types.REAL:
                    case Types.DOUBLE:
                    case Types.NUMERIC:
                    case Types.DECIMAL:
                    case Types.NULL:
                    case Types.OTHER:
                    case Types.JAVA_OBJECT:
                    case Types.DISTINCT:
                    case Types.STRUCT:
                    case Types.ARRAY:
                    case Types.REF:
                    case Types.DATALINK:
                    case Types.BOOLEAN:
                    case Types.ROWID:
                    case Types.NCHAR:
                    case Types.NVARCHAR:
                    case Types.LONGNVARCHAR:
                    case Types.NCLOB:
                    case Types.SQLXML:

                        // use getObject for all other known types

                        value.setValue(resultSet.getObject(i));
                        break;

                    default:

                        // otherwise try as string

                        asStringOrObject(value, resultSet, i);
                        break;
                    }

                } catch (Exception e) {

                    try {

                        // ... and on dump, resort to string
                        value.setValue(resultSet.getString(i));

                    } catch (SQLException sqlException) {

                        // catch-all SQLException - yes, this is hideous

                        // noticed with invalid date formatted values in mysql

                        value.setValue("<Error - " + sqlException.getMessage() + ">");
                    }
                }

                if (resultSet.wasNull()) {

                    value.setNull();
                }

                rowData.add(value);
            }

            tableData.add(rowData);

            if (recordCount == maxRecords) {

                break;
            }

        }

        if (Log.isTraceEnabled()) {

            Log.trace("Finished populating table model - " + recordCount + " rows - [ "
                    + MiscUtils.formatDuration(System.currentTimeMillis() - time) + "]");
        }

        fireTableStructureChanged();

    } catch (SQLException e) {

        System.err.println("SQL error populating table model at: " + e.getMessage());
        Log.debug("Table model error - " + e.getMessage(), e);

    } catch (Exception e) {

        if (e instanceof InterruptedException) {

            Log.debug("ResultSet generation interrupted.", e);

        } else {

            String message = e.getMessage();
            if (StringUtils.isBlank(message)) {

                System.err.println("Exception populating table model.");

            } else {

                System.err.println("Exception populating table model at: " + message);
            }

            Log.debug("Table model error - ", e);
        }

    } finally {

        if (resultSet != null) {

            try {

                resultSet.close();

                Statement statement = resultSet.getStatement();
                if (statement != null) {

                    statement.close();
                }

            } catch (SQLException e) {
            }

        }
    }

}

From source file:org.voltdb.HsqlBackend.java

public VoltTable runDML(String dml) {
    dml = dml.trim();//w  ww . j  a  v a  2  s . c  o m
    String indicator = dml.substring(0, 1).toLowerCase();
    if (indicator.equals("s") || // "s" is for "select ..."
            indicator.equals("(")) { // "(" is for "(select ... UNION ...)" et. al.
        try {
            Statement stmt = dbconn.createStatement();
            sqlLog.l7dlog(Level.DEBUG, LogKeys.sql_Backend_ExecutingDML.name(), new Object[] { dml }, null);
            sqlLog.debug("Executing " + dml);
            ResultSet rs = stmt.executeQuery(dml);
            ResultSetMetaData rsmd = rs.getMetaData();

            // note the index values here carefully
            VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String colname = rsmd.getColumnLabel(i);
                String type = rsmd.getColumnTypeName(i);
                //LOG.fine("Column type: " + type);
                if (type.equals("VARCHAR"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.STRING);
                else if (type.equals("TINYINT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.TINYINT);
                else if (type.equals("SMALLINT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.SMALLINT);
                else if (type.equals("INTEGER"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.INTEGER);
                else if (type.equals("BIGINT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.BIGINT);
                else if (type.equals("DECIMAL"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.DECIMAL);
                else if (type.equals("FLOAT"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.FLOAT);
                else if (type.equals("TIMESTAMP"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.TIMESTAMP);
                else if (type.equals("VARBINARY"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.VARBINARY);
                else if (type.equals("CHARACTER"))
                    columns[i - 1] = new VoltTable.ColumnInfo(colname, VoltType.STRING);
                else
                    throw new ExpectedProcedureException(
                            "Trying to create a column in Backend with a (currently) unsupported type: "
                                    + type);
            }
            VoltTable table = new VoltTable(columns);
            while (rs.next()) {
                Object[] row = new Object[table.getColumnCount()];
                for (int i = 0; i < table.getColumnCount(); i++) {
                    if (table.getColumnType(i) == VoltType.STRING)
                        row[i] = rs.getString(i + 1);
                    else if (table.getColumnType(i) == VoltType.TINYINT)
                        row[i] = rs.getByte(i + 1);
                    else if (table.getColumnType(i) == VoltType.SMALLINT)
                        row[i] = rs.getShort(i + 1);
                    else if (table.getColumnType(i) == VoltType.INTEGER)
                        row[i] = rs.getInt(i + 1);
                    else if (table.getColumnType(i) == VoltType.BIGINT)
                        row[i] = rs.getLong(i + 1);
                    else if (table.getColumnType(i) == VoltType.DECIMAL)
                        row[i] = rs.getBigDecimal(i + 1);
                    else if (table.getColumnType(i) == VoltType.FLOAT)
                        row[i] = rs.getDouble(i + 1);
                    else if (table.getColumnType(i) == VoltType.VARBINARY)
                        row[i] = rs.getBytes(i + 1);
                    else if (table.getColumnType(i) == VoltType.TIMESTAMP) {
                        Timestamp t = rs.getTimestamp(i + 1);
                        if (t == null) {
                            row[i] = null;
                        } else {
                            // convert from millisecond to microsecond granularity
                            row[i] = new org.voltdb.types.TimestampType(t.getTime() * 1000);
                        }
                    } else {
                        throw new ExpectedProcedureException(
                                "Trying to read a (currently) unsupported type from a JDBC resultset.");
                    }
                    if (rs.wasNull()) {
                        // JDBC returns 0/0.0 instead of null. Put null into the row.
                        row[i] = null;
                    }
                }

                table.addRow(row);
            }
            stmt.close();
            rs.close();
            return table;
        } catch (Exception e) {
            if (e instanceof ExpectedProcedureException) {
                throw (ExpectedProcedureException) e;
            }
            sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e);
            throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e);
        }
    } else {
        try {
            Statement stmt = dbconn.createStatement();
            sqlLog.debug("Executing: " + dml);
            long ucount = stmt.executeUpdate(dml);
            sqlLog.debug("  result: " + String.valueOf(ucount));
            VoltTable table = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT));
            table.addRow(ucount);
            return table;
        } catch (SQLException e) {
            // glorious hack to determine if the error is a constraint failure
            if (e.getMessage().contains("constraint")) {
                sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_ConvertingHSQLExtoCFEx.name(), e);
                final byte messageBytes[] = e.getMessage().getBytes();
                ByteBuffer b = ByteBuffer.allocate(25 + messageBytes.length);
                b.putInt(messageBytes.length);
                b.put(messageBytes);
                b.put(e.getSQLState().getBytes());
                b.putInt(0); // ConstraintFailure.type
                try {
                    FastSerializer.writeString("HSQL", b);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                b.putInt(0);//Table size is 0
                b.rewind();
                throw new ConstraintFailureException(b);
            } else {
                sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e);
                throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e);
            }

        } catch (Exception e) {
            // rethrow an expected exception
            sqlLog.l7dlog(Level.TRACE, LogKeys.sql_Backend_DmlError.name(), e);
            throw new ExpectedProcedureException("HSQLDB Backend DML Error ", e);
        }
    }
}

From source file:org.moqui.impl.entity.EntityJavaUtil.java

public static Object getResultSetValue(ResultSet rs, int index, FieldInfo fi, EntityFacade efi)
        throws EntityException {
    if (fi.typeValue == -1)
        throw new EntityException("No typeValue found for " + fi.entityName + "." + fi.name);

    Object value = null;//from w  ww.  j a  v a  2  s  .c om
    try {
        switch (fi.typeValue) {
        case 1:
            // getMetaData and the column type are somewhat slow (based on profiling), and String values are VERY
            //     common, so only do for text-very-long
            if (fi.isTextVeryLong) {
                ResultSetMetaData rsmd = rs.getMetaData();
                if (Types.CLOB == rsmd.getColumnType(index)) {
                    // if the String is empty, try to get a text input stream, this is required for some databases
                    // for larger fields, like CLOBs
                    Clob valueClob = rs.getClob(index);
                    Reader valueReader = null;
                    if (valueClob != null)
                        valueReader = valueClob.getCharacterStream();
                    if (valueReader != null) {
                        // read up to 4096 at a time
                        char[] inCharBuffer = new char[4096];
                        StringBuilder strBuf = new StringBuilder();
                        try {
                            int charsRead;
                            while ((charsRead = valueReader.read(inCharBuffer, 0, 4096)) > 0) {
                                strBuf.append(inCharBuffer, 0, charsRead);
                            }
                            valueReader.close();
                        } catch (IOException e) {
                            throw new EntityException("Error reading long character stream for field ["
                                    + fi.name + "] of entity [" + fi.entityName + "]", e);
                        }
                        value = strBuf.toString();
                    }
                } else {
                    value = rs.getString(index);
                }
            } else {
                value = rs.getString(index);
            }
            break;
        case 2:
            try {
                value = rs.getTimestamp(index, efi.getCalendarForTzLc());
            } catch (SQLException e) {
                if (logger.isTraceEnabled())
                    logger.trace(
                            "Ignoring SQLException for getTimestamp(), leaving null (found this in MySQL with a date/time value of [0000-00-00 00:00:00]): "
                                    + e.toString());
            }
            break;
        case 3:
            value = rs.getTime(index, efi.getCalendarForTzLc());
            break;
        case 4:
            value = rs.getDate(index, efi.getCalendarForTzLc());
            break;
        case 5:
            int intValue = rs.getInt(index);
            if (!rs.wasNull())
                value = intValue;
            break;
        case 6:
            long longValue = rs.getLong(index);
            if (!rs.wasNull())
                value = longValue;
            break;
        case 7:
            float floatValue = rs.getFloat(index);
            if (!rs.wasNull())
                value = floatValue;
            break;
        case 8:
            double doubleValue = rs.getDouble(index);
            if (!rs.wasNull())
                value = doubleValue;
            break;
        case 9:
            BigDecimal bigDecimalValue = rs.getBigDecimal(index);
            if (!rs.wasNull())
                value = bigDecimalValue != null ? bigDecimalValue.stripTrailingZeros() : null;
            break;
        case 10:
            boolean booleanValue = rs.getBoolean(index);
            if (!rs.wasNull())
                value = booleanValue;
            break;
        case 11:
            Object obj = null;
            byte[] originalBytes = rs.getBytes(index);
            InputStream binaryInput = null;
            if (originalBytes != null && originalBytes.length > 0) {
                binaryInput = new ByteArrayInputStream(originalBytes);
            }
            if (originalBytes != null && originalBytes.length <= 0) {
                logger.warn("Got byte array back empty for serialized Object with length ["
                        + originalBytes.length + "] for field [" + fi.name + "] (" + index + ")");
            }
            if (binaryInput != null) {
                ObjectInputStream inStream = null;
                try {
                    inStream = new ObjectInputStream(binaryInput);
                    obj = inStream.readObject();
                } catch (IOException ex) {
                    if (logger.isTraceEnabled())
                        logger.trace("Unable to read BLOB from input stream for field [" + fi.name + "] ("
                                + index + "): " + ex.toString());
                } catch (ClassNotFoundException ex) {
                    if (logger.isTraceEnabled())
                        logger.trace("Class not found: Unable to cast BLOB data to an Java object for field ["
                                + fi.name + "] (" + index
                                + "); most likely because it is a straight byte[], so just using the raw bytes: "
                                + ex.toString());
                } finally {
                    if (inStream != null) {
                        try {
                            inStream.close();
                        } catch (IOException e) {
                            throw new EntityException("Unable to close binary input stream for field ["
                                    + fi.name + "] (" + index + "): " + e.toString(), e);
                        }
                    }
                }
            }
            if (obj != null) {
                value = obj;
            } else {
                value = originalBytes;
            }
            break;
        case 12:
            SerialBlob sblob = null;
            try {
                // NOTE: changed to try getBytes first because Derby blows up on getBlob and on then calling getBytes for the same field, complains about getting value twice
                byte[] fieldBytes = rs.getBytes(index);
                if (!rs.wasNull())
                    sblob = new SerialBlob(fieldBytes);
                // fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null
            } catch (SQLException e) {
                if (logger.isTraceEnabled())
                    logger.trace("Ignoring exception trying getBytes(), trying getBlob(): " + e.toString());
                Blob theBlob = rs.getBlob(index);
                if (!rs.wasNull())
                    sblob = new SerialBlob(theBlob);
            }
            value = sblob;
            break;
        case 13:
            value = new SerialClob(rs.getClob(index));
            break;
        case 14:
        case 15:
            value = rs.getObject(index);
            break;
        }
    } catch (SQLException sqle) {
        logger.error("SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle);
        throw new EntityException(
                "SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle);
    }

    return value;
}

From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java

private Object processColumn(ResultSet rs, int index, Class<?> propType, String writer, StringBuilder handler)
        throws SQLException {
    if (propType.equals(String.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getString(").append(index).append("));");
        return rs.getString(index);
    } else if (propType.equals(Integer.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getInt(").append(index).append("));");
        return rs.getInt(index);
    } else if (propType.equals(Integer.class)) {
        handler.append("bean.").append(writer).append("(").append("integerValue($1.getInt(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Integer.class);
    } else if (propType.equals(Long.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getLong(").append(index).append("));");
        return rs.getLong(index);
    } else if (propType.equals(Long.class)) {
        handler.append("bean.").append(writer).append("(").append("longValue($1.getLong(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Long.class);
    } else if (propType.equals(java.sql.Date.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getDate(").append(index).append("));");
        return rs.getDate(index);
    } else if (propType.equals(java.util.Date.class) || propType.equals(Timestamp.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getTimestamp(").append(index)
                .append("));");
        return rs.getTimestamp(index);
    } else if (propType.equals(Double.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getDouble(").append(index).append("));");
        return rs.getDouble(index);
    } else if (propType.equals(Double.class)) {
        handler.append("bean.").append(writer).append("(").append("doubleValue($1.getDouble(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Double.class);
    } else if (propType.equals(Float.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getFloat(").append(index).append("));");
        return rs.getFloat(index);
    } else if (propType.equals(Float.class)) {
        handler.append("bean.").append(writer).append("(").append("floatValue($1.getFloat(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Float.class);
    } else if (propType.equals(Time.class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getTime(").append(index).append("));");
        return rs.getTime(index);
    } else if (propType.equals(Boolean.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBoolean(").append(index).append("));");
        return rs.getBoolean(index);
    } else if (propType.equals(Boolean.class)) {
        handler.append("bean.").append(writer).append("(").append("booleanValue($1.getBoolean(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Boolean.class);
    } else if (propType.equals(byte[].class)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBytes(").append(index).append("));");
        return rs.getBytes(index);
    } else if (BigDecimal.class.equals(propType)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBigDecimal(").append(index)
                .append("));");
        return rs.getBigDecimal(index);
    } else if (Blob.class.equals(propType)) {
        handler.append("bean.").append(writer).append("(").append("$1.getBlob(").append(index).append("));");
        return rs.getBlob(index);
    } else if (Clob.class.equals(propType)) {
        handler.append("bean.").append(writer).append("(").append("$1.getClob(").append(index).append("));");
        return rs.getClob(index);
    } else if (propType.equals(Short.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getShort(").append(index).append("));");
        return rs.getShort(index);
    } else if (propType.equals(Short.class)) {
        handler.append("bean.").append(writer).append("(").append("shortValue($1.getShort(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Short.class);
    } else if (propType.equals(Byte.TYPE)) {
        handler.append("bean.").append(writer).append("(").append("$1.getByte(").append(index).append("));");
        return rs.getByte(index);
    } else if (propType.equals(Byte.class)) {
        handler.append("bean.").append(writer).append("(").append("byteValue($1.getByte(").append(index)
                .append("),$1.wasNull()));");
        return JdbcUtils.getResultSetValue(rs, index, Byte.class);
    } else {/*from  w w  w.j  av a  2  s . c o  m*/
        handler.append("bean.").append(writer).append("(").append("(").append(propType.getName()).append(")")
                .append("$1.getObject(").append(index).append("));");
        return rs.getObject(index);
    }
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

private Object processColumn(ResultSet rs, int index, Class<?> propType, String writer, String processorName,
        String beanName, MethodVisitor mv) throws SQLException {

    if (propType.equals(String.class)) {
        visitMethod(mv, index, beanName, "Ljava/lang/String;", "getString", writer);
        return rs.getString(index);
    } else if (propType.equals(Integer.TYPE)) {
        visitMethod(mv, index, beanName, "I", "getInt", writer);
        return rs.getInt(index);
    } else if (propType.equals(Integer.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_INTEGER, writer, processorName);
        return JdbcUtils.getResultSetValue(rs, index, Integer.class);
    } else if (propType.equals(Long.TYPE)) {
        visitMethod(mv, index, beanName, "J", "getLong", writer);
        return rs.getLong(index);
    } else if (propType.equals(Long.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_LONG, writer, processorName);
        return JdbcUtils.getResultSetValue(rs, index, Long.class);
    } else if (propType.equals(java.sql.Date.class)) {
        visitMethod(mv, index, beanName, "Ljava/sql/Date;", "getDate", writer);
        return rs.getDate(index);
    } else if (propType.equals(java.util.Date.class)) {
        visitMethodCast(mv, index, beanName, PROPERTY_TYPE_DATE, "java/util/Date", writer);
        return rs.getTimestamp(index);
    } else if (propType.equals(Timestamp.class)) {
        visitMethod(mv, index, beanName, "Ljava/sql/Timestamp;", "getTimestamp", writer);
        return rs.getTimestamp(index);
    } else if (propType.equals(Time.class)) {
        visitMethod(mv, index, beanName, "Ljava/sql/Time;", "getTime", writer);
        return rs.getTime(index);
    } else if (propType.equals(Double.TYPE)) {
        visitMethod(mv, index, beanName, "D", "getDouble", writer);
        return rs.getDouble(index);
    } else if (propType.equals(Double.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_DOUBLE, writer, processorName);
        return JdbcUtils.getResultSetValue(rs, index, Double.class);
    } else if (propType.equals(Float.TYPE)) {
        visitMethod(mv, index, beanName, "F", "getFloat", writer);
        return rs.getFloat(index);
    } else if (propType.equals(Float.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_FLOAT, writer, processorName);
        return JdbcUtils.getResultSetValue(rs, index, Float.class);
    } else if (propType.equals(Boolean.TYPE)) {
        visitMethod(mv, index, beanName, "Z", "getBoolean", writer);
        return rs.getBoolean(index);
    } else if (propType.equals(Boolean.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_BOOLEAN, writer, processorName);
        return JdbcUtils.getResultSetValue(rs, index, Boolean.class);
    } else if (propType.equals(Clob.class)) {
        visitMethod(mv, index, beanName, "Ljava/sql/Clob;", "getClob", writer);
        return rs.getClob(index);
    } else if (propType.equals(Blob.class)) {
        visitMethod(mv, index, beanName, "Ljava/sql/Blob;", "getBlob", writer);
        return rs.getBlob(index);
    } else if (propType.equals(byte[].class)) {
        visitMethod(mv, index, beanName, "[B", "getBytes", writer);
        return rs.getBytes(index);
    } else if (propType.equals(Short.TYPE)) {
        visitMethod(mv, index, beanName, "S", "getShort", writer);
        return rs.getShort(index);
    } else if (propType.equals(Short.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_SHORT, writer, processorName);
        return JdbcUtils.getResultSetValue(rs, index, Short.class);
    } else if (propType.equals(Byte.TYPE)) {
        visitMethod(mv, index, beanName, "B", "getByte", writer);
        return rs.getByte(index);
    } else if (propType.equals(Byte.class)) {
        visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_BYTE, writer, processorName);
        return rs.getByte(index);
    } else {/* ww  w . j av a2s .co m*/
        visitMethodCast(mv, index, beanName, PROPERTY_TYPE_OTHER, propType.getName().replace('.', '/'), writer);
        return rs.getObject(index);
    }
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * This is the core method to retrieve a value for a column from a result set. Its  primary
 * purpose is to call the appropriate method on the result set, and to provide an extension
 * point where database-specific implementations can change this behavior.
 * /*from w  w w  .  j  a  v a 2  s .c  o  m*/
 * @param resultSet  The result set to extract the value from
 * @param columnName The name of the column; can be <code>null</code> in which case the
  *                   <code>columnIdx</code> will be used instead
  * @param columnIdx  The index of the column's value in the result set; is only used if
  *                   <code>columnName</code> is <code>null</code>
 * @param jdbcType   The jdbc type to extract
 * @return The value
 * @throws SQLException If an error occurred while accessing the result set
 */
protected Object extractColumnValue(ResultSet resultSet, String columnName, int columnIdx, int jdbcType)
        throws SQLException {
    boolean useIdx = (columnName == null);
    Object value;

    switch (jdbcType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        value = useIdx ? resultSet.getString(columnIdx) : resultSet.getString(columnName);
        break;
    case Types.NUMERIC:
    case Types.DECIMAL:
        value = useIdx ? resultSet.getBigDecimal(columnIdx) : resultSet.getBigDecimal(columnName);
        break;
    case Types.BIT:
    case Types.BOOLEAN:
        value = new Boolean(useIdx ? resultSet.getBoolean(columnIdx) : resultSet.getBoolean(columnName));
        break;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        value = new Integer(useIdx ? resultSet.getInt(columnIdx) : resultSet.getInt(columnName));
        break;
    case Types.BIGINT:
        value = new Long(useIdx ? resultSet.getLong(columnIdx) : resultSet.getLong(columnName));
        break;
    case Types.REAL:
        value = new Float(useIdx ? resultSet.getFloat(columnIdx) : resultSet.getFloat(columnName));
        break;
    case Types.FLOAT:
    case Types.DOUBLE:
        value = new Double(useIdx ? resultSet.getDouble(columnIdx) : resultSet.getDouble(columnName));
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        value = useIdx ? resultSet.getBytes(columnIdx) : resultSet.getBytes(columnName);
        break;
    case Types.DATE:
        value = useIdx ? resultSet.getDate(columnIdx) : resultSet.getDate(columnName);
        break;
    case Types.TIME:
        value = useIdx ? resultSet.getTime(columnIdx) : resultSet.getTime(columnName);
        break;
    case Types.TIMESTAMP:
        value = useIdx ? resultSet.getTimestamp(columnIdx) : resultSet.getTimestamp(columnName);
        break;
    case Types.CLOB:
        Clob clob = useIdx ? resultSet.getClob(columnIdx) : resultSet.getClob(columnName);

        if (clob == null) {
            value = null;
        } else {
            long length = clob.length();

            if (length > Integer.MAX_VALUE) {
                value = clob;
            } else if (length == 0) {
                // the javadoc is not clear about whether Clob.getSubString
                // can be used with a substring length of 0
                // thus we do the safe thing and handle it ourselves
                value = "";
            } else {
                value = clob.getSubString(1l, (int) length);
            }
        }
        break;
    case Types.BLOB:
        Blob blob = useIdx ? resultSet.getBlob(columnIdx) : resultSet.getBlob(columnName);

        if (blob == null) {
            value = null;
        } else {
            long length = blob.length();

            if (length > Integer.MAX_VALUE) {
                value = blob;
            } else if (length == 0) {
                // the javadoc is not clear about whether Blob.getBytes
                // can be used with for 0 bytes to be copied
                // thus we do the safe thing and handle it ourselves
                value = new byte[0];
            } else {
                value = blob.getBytes(1l, (int) length);
            }
        }
        break;
    case Types.ARRAY:
        value = useIdx ? resultSet.getArray(columnIdx) : resultSet.getArray(columnName);
        break;
    case Types.REF:
        value = useIdx ? resultSet.getRef(columnIdx) : resultSet.getRef(columnName);
        break;
    default:
        value = useIdx ? resultSet.getObject(columnIdx) : resultSet.getObject(columnName);
        break;
    }
    return resultSet.wasNull() ? null : value;
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *//*  w w  w  . ja  va2 s. co m*/
public ImageData getImageData(int fileId, int resized) throws SQLException {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = DatabaseConnection.getConnection();
        stmt = conn.prepareStatement(STATEMENT_SELECT_FILE_DATA);
        stmt.setInt(1, fileId);
        stmt.setInt(2, resized);
        rs = stmt.executeQuery();
        return (rs.next())
                ? new ImageData(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getBytes(5))
                : null;
    } finally {
        DatabaseConnection.closeConnection(conn, stmt, rs);
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *//* w  w w . ja  v a2 s .c om*/
public ImageData getImageVersionData(int fileVersionId, int resized) throws SQLException {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = DatabaseConnection.getConnection();
        stmt = conn.prepareStatement(STATEMENT_SELECT_FILE_VERSION_DATA);
        stmt.setInt(1, fileVersionId);
        stmt.setInt(2, resized);
        rs = stmt.executeQuery();
        return (rs.next())
                ? new ImageData(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getBytes(5))
                : null;
    } finally {
        DatabaseConnection.closeConnection(conn, stmt, rs);
    }
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Returns the photo with the given id using the given connection.
 * <p>Note that the connection is not closed at the end of the method
 * @param con the connection to use/*from   w ww  . jav  a2 s .  c  o  m*/
 * @param id the if
 * @return the photo, or null if not found
 * @throws DAOException if an error occurs
 */
public Photo getPhoto(Connection con, Long id) throws DAOException {

    Photo photo = null;

    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {

        stmt = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_CONTACT_PHOTO);
        stmt.setLong(1, id);
        stmt.setString(2, userId);

        rs = stmt.executeQuery();
        while (rs.next()) {
            photo = new Photo();
            photo.setType(rs.getString(2));
            photo.setImage(rs.getBytes(3));
            photo.setUrl(rs.getString(4));
        }

    } catch (Exception e) {
        throw new DAOException("Error retrieving photo with id: " + id, e);
    } finally {
        DBTools.close(null, stmt, rs);
    }
    return photo;
}