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.springframework.jdbc.support.lob.DefaultLobHandler.java

@Override
@Nullable/*  ww w . j ava2s .  com*/
public byte[] getBlobAsBytes(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning BLOB as bytes");
    if (this.wrapAsLob) {
        Blob blob = rs.getBlob(columnIndex);
        return blob.getBytes(1, (int) blob.length());
    } else {
        return rs.getBytes(columnIndex);
    }
}

From source file:wikipedia.sql.Links.java

/** Selects one pl_title from pagelinks by pl_from. It is needed for 
 * redirect pages, which links only to one page. 
 * @return null, if (1) it is absent (e.g. it's redirect to category) or 
 *                  (2) title should be skipped
 *///from  w  ww .j av a 2s .  c  om
public static String getTitleToOneByIDFrom(SessionHolder session, int pl_from) {
    if (0 == pl_from)
        return null;

    // special treatment of id of redirect page
    if (pl_from < 0)
        pl_from = -pl_from;

    Statement s = null;
    ResultSet rs = null;
    String title = null;

    sb.setLength(0);
    sb.append("SELECT pl_title FROM pagelinks WHERE pl_from=");
    sb.append(pl_from);
    sb.append(" LIMIT 1");

    try {
        s = session.connect.conn.createStatement();
        //str_sql = SELECT pl_title FROM pagelinks WHERE pl_from=52141 LIMIT 1;

        s.executeQuery(sb.toString());
        rs = s.getResultSet();

        if (rs.next()) {
            Encodings e = session.connect.enc;
            String db_str = Encodings.bytesTo(rs.getBytes("pl_title"), e.GetDBEnc());
            String utf8_str = e.EncodeFromDB(db_str);
            if (!session.skipTitle(utf8_str)) {
                title = utf8_str;
            }
        }
    } catch (SQLException ex) {
        System.err.println("SQLException (Links.java getTitleToOneByIDFrom): sql='" + sb.toString() + "' "
                + ex.getMessage());
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
            }
            rs = null;
        }
        if (s != null) {
            try {
                s.close();
            } catch (SQLException sqlEx) {
            }
            s = null;
        }
    }
    return title;
}

From source file:nz.co.gregs.dbvolution.datatypes.DBByteArray.java

private byte[] getFromGetBytes(ResultSet resultSet, String fullColumnName) throws SQLException {
    byte[] bytes = resultSet.getBytes(fullColumnName);
    //      this.setValue(bytes);
    return bytes;
}

From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java

/**
 * Retrieve the original file data associated with a specific entry ID
 * //from   www.j av a2 s .com
 * @return Bytes of the original file
 * @throws Exception TODO describe exception
 */
public byte[] getOriginalFile(String entryId) throws Exception {

    String sql = "SELECT file_data FROM reportedErrors WHERE entry_id = " + entryId;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet results = null;

    try {
        connection = getConnection();
        statement = connection.prepareStatement(sql);
        results = statement.executeQuery();
        results.next();

        return results.getBytes("file_data");
    } finally {
        if (results != null) {
            results.close();
        }

        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java

/**
 * Retrieve the output file data associated with a specific entry ID
 * //from   ww w . j a  va 2  s . co m
 * @return Output XML file
 * @throws Exception TODO describe exception
 */
public byte[] getOutputFile(String entryId) throws Exception {

    String sql = "SELECT output_xml FROM reportedErrors WHERE entry_id = " + entryId;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet results = null;

    try {
        connection = getConnection();
        statement = connection.prepareStatement(sql);
        results = statement.executeQuery();
        results.next();

        return results.getBytes("output_xml");
    } finally {
        if (results != null) {
            results.close();
        }

        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

@Override
public List<InetAddress> findExistingIPs(final InetAddress startAddr, final InetAddress endAddr) {
    return getJdbcTemplate().query("select ipaddress from dhcplease"
            + " where ipaddress >= ? and ipaddress <= ?" + " order by ipaddress",
            new PreparedStatementSetter() {
                @Override/*w w w.j ava2s .c o  m*/
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setBytes(1, startAddr.getAddress());
                    ps.setBytes(2, endAddr.getAddress());
                }
            }, new RowMapper<InetAddress>() {
                @Override
                public InetAddress mapRow(ResultSet rs, int rowNum) throws SQLException {
                    InetAddress inetAddr = null;
                    try {
                        inetAddr = InetAddress.getByAddress(rs.getBytes("ipaddress"));
                    } catch (UnknownHostException e) {
                        // re-throw as SQLException
                        throw new SQLException("Unable to map ipaddress", e);
                    }
                    return inetAddr;
                }
            });
}

From source file:org.miloss.fgsms.tools.DatabaseExport.java

private static void exportTable(Table table, Connection con, PrintWriter fos) throws Exception {
    fos.println();/*from  w  ww  .  j a  v  a  2 s  .co  m*/
    fos.println();
    fos.println();
    PreparedStatement prepareStatement = con.prepareStatement("select * from " + table.name + " ");

    StringBuilder sb = new StringBuilder("insert into " + table.name + "(");
    for (int i = 0; i < table.columns.size(); i++) {
        sb.append(table.columns.get(i).name).append(",");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(") VALUES (");
    final String header = sb.toString();
    prepareStatement.close();

    ResultSet executeQuery = prepareStatement.executeQuery();
    while (executeQuery.next()) {
        fos.write(header);
        for (int i = 0; i < table.columns.size(); i++) {

            switch (table.columns.get(i).type) {
            case BIGINT: {
                long val = executeQuery.getLong(table.columns.get(i).name);
                fos.write(val + "");
            }
                break;
            case INTEGER: {
                int vali = executeQuery.getInt(table.columns.get(i).name);
                fos.write(vali + "");
            }
                break;
            case BOOLEAN: {
                boolean valb = executeQuery.getBoolean(table.columns.get(i).name);
                fos.write(valb + "");
            }
                break;
            case VARCHAR: {
                String vals = executeQuery.getString(table.columns.get(i).name);
                fos.write("'" + escape(vals) + "'");
            }
                break;
            case DOUBLE: {
                double vals = executeQuery.getDouble(table.columns.get(i).name);
                fos.write(vals + "");
            }
                break;
            case BYTEA: {
                if (table.columns.get(i).isFgsmsEncrypted) {
                    byte[] bits = executeQuery.getBytes(table.columns.get(i).name);
                    if (bits != null) {
                        String clear = Utility.DE(new String(bits));
                        bits = clear.getBytes(Constants.CHARSET);
                        fos.write("E'\\x" + bytesToHex(bits) + "'");
                    } else {
                        fos.write("NULL");
                    }

                } else {
                    //dunno?
                    String vals = new String(executeQuery.getBytes(table.columns.get(i).name));
                    fos.write("E'\\x" + bytesToHex(vals.getBytes()) + "'");
                }
            }
                break;
            default:
                throw new Exception("unhandled case for " + table.name + "," + table.columns.get(i).name);
            }
            if (i + 1 != table.columns.size()) {
                fos.write(",");
            }
        }

        fos.write(");\n");
    }
    executeQuery.close();
    prepareStatement.close();

}

From source file:bd.gov.forms.dao.FormDaoImpl.java

public byte[] getTemplateContent(String formId) {
    Form form = (Form) jdbcTemplate.queryForObject("SELECT template_file FROM form WHERE form_id = ?",
            new Object[] { formId }, new RowMapper() {

                public Object mapRow(ResultSet resultSet, int rowNum) throws SQLException {
                    Form form = new Form();

                    form.setPdfTemplate(resultSet.getBytes("template_file"));

                    return form;
                }//w w w  . j  av a 2  s  . c  o  m
            });

    return form.getPdfTemplate();
}

From source file:org.opendatakit.persistence.engine.pgres.RelationRowMapper.java

@Override
public CommonFieldsBase mapRow(ResultSet rs, int rowNum) throws SQLException {

    CommonFieldsBase row;//from  w w w .  ja  v  a2 s.c o  m
    try {
        row = relation.getEmptyRow(user);
        row.setFromDatabase(true);
    } catch (Exception e) {
        throw new IllegalStateException("failed to create empty row", e);
    }

    /**
     * Correct for the funky handling of nulls by the various accessors...
     */
    for (DataField f : relation.getFieldList()) {
        switch (f.getDataType()) {
        case BINARY:
            byte[] blobBytes = rs.getBytes(f.getName());
            row.setBlobField(f, blobBytes);
            break;
        case LONG_STRING:
        case URI:
        case STRING:
            row.setStringField(f, rs.getString(f.getName()));
            break;
        case INTEGER:
            long l = rs.getLong(f.getName());
            if (rs.wasNull()) {
                row.setLongField(f, null);
            } else {
                row.setLongField(f, Long.valueOf(l));
            }
            break;
        case DECIMAL: {
            String value = rs.getString(f.getName());
            if (value == null) {
                row.setNumericField(f, null);
            } else {
                row.setNumericField(f, new WrappedBigDecimal(value));
            }
        }
            break;
        case BOOLEAN:
            Boolean b = rs.getBoolean(f.getName());
            if (rs.wasNull()) {
                row.setBooleanField(f, null);
            } else {
                row.setBooleanField(f, b);
            }
            break;
        case DATETIME:
            Date d = rs.getTimestamp(f.getName());
            if (d == null) {
                row.setDateField(f, null);
            } else {
                row.setDateField(f, (Date) d.clone());
            }
            break;
        default:
            throw new IllegalStateException("Did not expect non-primitive type in column fetch");
        }
    }
    return row;
}

From source file:jm.web.Archivo.java

public String getArchivo(String path, int clave) {
    this._archivoNombre = "";
    try {/*from  w w  w .ja  v a  2  s.  c o  m*/
        ResultSet res = this.consulta("select * from tbl_archivo where id_archivo=" + clave + ";");
        if (res.next()) {
            this._archivoNombre = (res.getString("nombre") != null) ? res.getString("nombre") : "";
            try {
                this._archivo = new File(path, this._archivoNombre);
                if (!this._archivo.exists()) {
                    byte[] bytes = (res.getString("archivo") != null) ? res.getBytes("archivo") : null;
                    RandomAccessFile archivo = new RandomAccessFile(path + this._archivoNombre, "rw");
                    archivo.write(bytes);
                    archivo.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}