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.jumpmind.db.platform.interbase.InterbaseDdlReader.java

protected void determineExtraColumnInfo(Connection connection, Table table) throws SQLException {
    StringBuffer query = new StringBuffer();

    query.append("SELECT a.RDB$FIELD_NAME, a.RDB$DEFAULT_SOURCE, b.RDB$FIELD_PRECISION, b.RDB$FIELD_SCALE,");
    query.append(" b.RDB$FIELD_TYPE, b.RDB$FIELD_SUB_TYPE FROM RDB$RELATION_FIELDS a, RDB$FIELDS b");
    query.append(" WHERE a.RDB$RELATION_NAME=? AND a.RDB$FIELD_SOURCE=b.RDB$FIELD_NAME");

    PreparedStatement prepStmt = connection.prepareStatement(query.toString());

    try {/*from  w  w w .  j a  v  a 2s.co m*/
        prepStmt.setString(1, getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn() ? table.getName()
                : table.getName().toUpperCase());

        ResultSet rs = prepStmt.executeQuery();

        while (rs.next()) {
            String columnName = rs.getString(1).trim();
            Column column = table.findColumn(columnName,
                    getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn());

            if (column != null) {
                byte[] defaultBytes = rs.getBytes(2);
                String defaultValue = defaultBytes != null ? new String(defaultBytes) : null;

                if (!rs.wasNull() && (defaultValue != null)) {
                    defaultValue = defaultValue.trim();
                    if (defaultValue.startsWith("DEFAULT ")) {
                        defaultValue = defaultValue.substring("DEFAULT ".length());
                    }
                    column.setDefaultValue(defaultValue);
                }

                short precision = rs.getShort(3);
                boolean precisionSpecified = !rs.wasNull();
                short scale = rs.getShort(4);
                boolean scaleSpecified = !rs.wasNull();

                if (precisionSpecified) {
                    // for some reason, Interbase stores the negative scale
                    column.setSizeAndScale(precision, scaleSpecified ? -scale : 0);
                }

                short dbType = rs.getShort(5);
                short blobSubType = rs.getShort(6);

                // CLOBs are returned by the driver as VARCHAR
                if (!rs.wasNull() && (dbType == 261) && (blobSubType == 1)) {
                    column.setMappedTypeCode(Types.CLOB);
                }
            }
        }
        rs.close();
    } finally {
        prepStmt.close();
    }
}

From source file:at.becast.youploader.youtube.playlists.PlaylistManager.java

public void load() {
    if (playlists.isEmpty()) {
        Connection c = SQLite.getInstance();
        Statement stmt;/* www  .j a  v a2  s  .c o  m*/
        try {
            stmt = c.createStatement();
            String sql = "SELECT * FROM `playlists`";
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.isBeforeFirst()) {
                while (rs.next()) {
                    String shown;
                    if (rs.getString("shown") == null) {
                        shown = "1";
                        SQLite.setPlaylistHidden(rs.getInt("id"), shown);
                    } else {
                        shown = rs.getString("shown");
                    }
                    Playlist l = new Playlist(rs.getInt("id"), rs.getString("playlistid"), rs.getString("name"),
                            rs.getBytes("image"), shown);
                    if (playlists.get(rs.getInt("account")) == null) {
                        List<Playlist> list = new ArrayList<Playlist>();
                        list.add(l);
                        playlists.put(rs.getInt("account"), list);
                    } else {
                        playlists.get(rs.getInt("account")).add(l);
                    }
                }
                rs.close();
                stmt.close();
            } else {
                rs.close();
                stmt.close();
            }
        } catch (SQLException e) {
            LOG.error("Error loading playlists", e);
        }
    }
}

From source file:com.fluidops.iwb.wiki.WikiSQLStorageBase.java

@Override
public String getWikiContent(URI resource, WikiRevision revision) {
    PreparedStatement stat = null;
    ResultSet rs = null;
    try {/*  ww w  .  ja  va2s  .  co m*/
        Connection conn = getConnection();
        stat = conn.prepareStatement("select content from revisions where name=? and date=?");
        stat.setString(1, resource.stringValue());
        stat.setLong(2, revision.date.getTime());

        rs = stat.executeQuery();
        SQL.monitorRead();
        if (rs.next()) {
            if (com.fluidops.iwb.util.Config.getConfig().getCompressWikiInDatabase())
                return gunzip(rs.getBytes("content"));
            else
                return rs.getString("content");
        }
        return null;
    } catch (SQLException e) {
        SQL.monitorReadFailure();
        throw new RuntimeException("Retrieving wiki content failed.", e);
    } finally {
        SQL.closeQuietly(rs);
        SQL.closeQuietly(stat);
    }
}

From source file:com.akman.excel.view.frmExportExcel.java

public BufferedImage getSignature() {
    Connection conn = Javaconnect.ConnecrDb();
    PreparedStatement pst = null;
    ResultSet rs = null;

    BufferedImage img = null;//from w  w  w .  j  a v a  2  s .co m
    try {

        String sql = "SELECT MAX(ID), Image FROM ExcelData";

        pst = conn.prepareStatement(sql);

        rs = pst.executeQuery();

        if (rs.next()) {

            byte[] blob = rs.getBytes("Image");
            InputStream in = new ByteArrayInputStream(blob);
            img = ImageIO.read(in);

        }

    } catch (SQLException ex) {
        Logger.getLogger(frmSelectImage.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(frmExportExcel.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pst);
        DbUtils.closeQuietly(conn);
    }

    return img;
}

From source file:jm.web.Archivo.java

public String getArchivo(String path, String tabla, String clave, String campoNombre, String campoBytea) {
    this._archivoNombre = "";
    try {//from   w  w w .j  a  v  a2 s  . c  om
        ResultSet res = this.consulta(
                "select * from " + tabla + " where " + tabla.replace("tbl_", "id_") + "=" + clave + ";");
        if (res.next()) {
            this._archivoNombre = res.getString(campoNombre) != null ? res.getString(campoNombre) : "";
            if (this._archivoNombre.compareTo("") != 0) {
                try {
                    this._archivo = new File(path, this._archivoNombre);
                    if (!this._archivo.exists()) {
                        byte[] bytes = (res.getString(campoBytea) != null) ? res.getBytes(campoBytea) : 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;
}

From source file:org.glom.web.server.OnlineGlomImagesServlet.java

/** Get the image from a specific field of a specific record in a specific table in the database.
 * // w  w  w  .j  a v  a2  s. c o m
 * @param resp
 * @param attrDocumentID
 * @param attrTableName
 * @param attrPrimaryKeyValue
 * @param attrFieldName
 * @param configuredDocument
 * @param document
 * @return
 * @throws IOException
 */
private byte[] getImageFromDatabase(final HttpServletRequest request, final HttpServletResponse resp,
        final String attrDocumentID, final String attrTableName, final String attrPrimaryKeyValue,
        final String attrFieldName, final ConfiguredDocument configuredDocument, final Document document)
        throws IOException {
    final Field field = document.getField(attrTableName, attrFieldName);
    if (field == null) {
        doError(resp, Response.SC_NOT_FOUND, "The specified field was not found: field=" + attrFieldName,
                attrDocumentID);
        return null;
    }

    final Field fieldPrimaryKey = document.getTablePrimaryKeyField(attrTableName);

    TypedDataItem primaryKeyValue = new TypedDataItem();
    primaryKeyValue.setNumber(Double.parseDouble(attrPrimaryKeyValue));

    final LayoutItemField layoutItemField = new LayoutItemField();
    layoutItemField.setFullFieldDetails(field);
    final List<LayoutItemField> fieldsToGet = new ArrayList<LayoutItemField>();
    fieldsToGet.add(layoutItemField);
    final String query = SqlUtils.buildSqlSelectWithKey(attrTableName, fieldsToGet, fieldPrimaryKey,
            primaryKeyValue, document.getSqlDialect());

    final ComboPooledDataSource authenticatedConnection = getConnection(request, attrDocumentID);
    if (authenticatedConnection == null) {
        return null;
    }

    ResultSet rs = null;
    try {
        rs = SqlUtils.executeQuery(authenticatedConnection, query);
    } catch (SQLException e) {
        doError(resp, Response.SC_INTERNAL_SERVER_ERROR, "SQL exception: " + e.getMessage(), attrDocumentID);
        return null;
    }

    if (rs == null) {
        doError(resp, Response.SC_INTERNAL_SERVER_ERROR, "The SQL result set is null.", attrDocumentID);
        return null;
    }

    byte[] bytes = null;
    try {
        rs.next();
        bytes = rs.getBytes(1); //This is 1-indexed, not 0-indexed.
    } catch (SQLException e) {
        doError(resp, Response.SC_INTERNAL_SERVER_ERROR, "SQL exception: " + e.getMessage(), attrDocumentID);
        return null;
    }

    if (bytes == null) {
        doError(resp, Response.SC_INTERNAL_SERVER_ERROR, "The database contained null.", attrDocumentID);
        return null;
    }

    return bytes;
}

From source file:lineage2.gameserver.cache.CrestCache.java

/**
 * Method load.//from w w  w  .  ja  va  2 s  .com
 */
public void load() {
    int count = 0;
    int pledgeId, crestId;
    byte[] crest;
    Connection con = null;
    PreparedStatement statement = null;
    ResultSet rset = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement("SELECT clan_id, crest FROM clan_data WHERE crest IS NOT NULL");
        rset = statement.executeQuery();
        while (rset.next()) {
            count++;
            pledgeId = rset.getInt("clan_id");
            crest = rset.getBytes("crest");
            crestId = getCrestId(pledgeId, crest);
            _pledgeCrestId.put(pledgeId, crestId);
            _pledgeCrest.put(crestId, crest);
        }
        DbUtils.close(statement, rset);
        statement = con
                .prepareStatement("SELECT clan_id, largecrest FROM clan_data WHERE largecrest IS NOT NULL");
        rset = statement.executeQuery();
        while (rset.next()) {
            count++;
            pledgeId = rset.getInt("clan_id");
            crest = rset.getBytes("largecrest");
            crestId = getCrestId(pledgeId, crest);
            _pledgeCrestLargeId.put(pledgeId, crestId);
            get_pledgeCrestLarge().put(crestId, crest);
        }
        DbUtils.close(statement, rset);
        statement = con.prepareStatement("SELECT ally_id, crest FROM ally_data WHERE crest IS NOT NULL");
        rset = statement.executeQuery();
        while (rset.next()) {
            count++;
            pledgeId = rset.getInt("ally_id");
            crest = rset.getBytes("crest");
            crestId = getCrestId(pledgeId, crest);
            _allyCrestId.put(pledgeId, crestId);
            _allyCrest.put(crestId, crest);
        }
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        DbUtils.closeQuietly(con, statement, rset);
    }
    _log.info("CrestCache: Loaded " + count + " crests");
}

From source file:com.bt.aloha.dao.StateInfoDaoTest.java

private List<SimpleTestInfo> retrieveSimpleTestInfo() {
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {//www  .  j  a v  a 2 s.  c o  m
        List<SimpleTestInfo> l = new ArrayList<SimpleTestInfo>();
        statement = connection.prepareStatement("select * from StateInfo where object_type='SimpleTestInfo'");
        rs = statement.executeQuery();
        while (rs.next()) {
            byte[] bytes = rs.getBytes("object_value");
            ObjectInputStream oip = new ObjectInputStream(new ByteArrayInputStream(bytes));
            SimpleTestInfo info = (SimpleTestInfo) oip.readObject();
            l.add(info);
        }
        return l;
    } catch (SQLException e) {
        throw new IllegalStateException("Unable to retrieve from SimpleTestInfo");
    } catch (IOException e) {
        throw new IllegalStateException("Unable to create ObjectInputStream");
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Unable to read object");
    } finally {
        if (rs != null)
            try {
                rs.close();
            } catch (SQLException e) {
            }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:eu.europa.esig.dss.client.crl.JdbcCacheCRLSource.java

/**
 * Get the cached CRL from the datasource
 *
 * @param key the key of the CRL/*from www .  j  ava  2s .com*/
 * @return the cached crl
 * @throws java.sql.SQLException
 */
private CachedCRL findCrlInDB(String key) throws SQLException {

    Connection c = null;
    PreparedStatement s = null;
    ResultSet rs = null;
    try {
        c = getDataSource().getConnection();
        s = c.prepareStatement(sqlFindQuery);
        s.setString(1, key);
        rs = s.executeQuery();
        if (rs.next()) {
            CachedCRL cached = new CachedCRL();
            cached.setKey(rs.getString(sqlFindQueryId));
            cached.setCrl(rs.getBytes(sqlFindQueryData));
            return cached;
        }
    } finally {
        closeQuietly(c, s, rs);
    }

    return null;
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void loadDeviceList(Connection con, ShareMetaData smd, PublicKey masterPubKey)
        throws SQLException, SignatureException, NumberFormatException, InitializaionException {

    DeviceList list = smd.deviceLists.get(masterPubKey);
    if (list == null) {
        list = new DeviceList(masterPubKey, null);
        smd.deviceLists.put(masterPubKey, list);
    }//  w  w w  . j ava2  s.  co m

    PreparedStatement s = con.prepareStatement(QUERY_DEVICE_LIST);
    ResultSet rs = s.executeQuery();
    while (rs.next()) {
        String device = rs.getString(COL_DEV_ALIAS);
        logger.debug("Loading device: " + device);
        PublicKey devicePubKey = CryptCore.createPublicKeyFromBytes(rs.getBytes(COL_DEV_PUB_KEY));
        list.addDevice(device, devicePubKey);
    }
    rs.close();
    s.close();

    loadKeyValues(con, smd);

    loadDeviceListSignature(con, smd, masterPubKey, list);
}