Monday, 16 June 2014

Add BLOB to DB in Java using JDBC

  

    byte[] buffer= {(byte)0xC9, (byte)0xCB, (byte)0xBB,

            (byte)0xCC, (byte)0xCE, (byte)0xB9,

            (byte)0xC8, (byte)0xCA, (byte)0xBC,

            (byte)0xCC, (byte)0xCE, (byte)0xB9,

            (byte)0xC9, (byte)0xCB, (byte)0xBB};

     PreparedStatement pstmt = con.prepareStatement(query);

    pstmt.setBytes(1, buffer);

    Examples :

   public static void addTXN_DATA(String query, byte[] buffer,

            String entryMode, String verifyResult, double actAmt, double tipAmt) {

        try {
            connect();
            PreparedStatement pstmt = con.prepareStatement(query);
            pstmt.setBytes(1, buffer);
            pstmt.setString(2, entryMode);
            pstmt.setString(3, verifyResult);
            pstmt.setDouble(4, actAmt);
            pstmt.setDouble(5, tipAmt);
            log.debug("BINARY- TXN_DATA-" + Util.byteArrayToHexString(buffer));
            int count = pstmt.executeUpdate();
            con.commit();

            log.debug("Succesfully Added to DB BLOB " + count);

        } catch (DatastoreException e) {
            log.debug("While Updating the TXn info to DB", e);
        } catch (SQLException e) {
            log.debug("While Updating the TXn info to DB", e);
        }
    }

    public static byte[] getTXN_DATA(String ref) {
        try {
            connect();
            // Prepare a Statement:
           PreparedStatement stmnt = con.prepareStatement("SELECT TXN_DATA FROM TNX WHERE REF = "+ ref);
            // Execute
            ResultSet rs = stmnt.executeQuery();
            while (rs.next()) {
                try {
                    // Get as a BLOB
                    Blob aBlob = rs.getBlob(1);
                   byte[] allBytesInBlob = aBlob.getBytes(1,(int) aBlob.length());
                    return allBytesInBlob;
                } catch (Exception ex) {
                    // The driver could not handle this as a BLOB...
                    // Fallback to default (and slower) byte[] handling
                    byte[] bytes = rs.getBytes(1);
                    return bytes;
                }
            }
            // Close resources
            rs.close();
            stmnt.close();
        } catch (Exception ex) {
            log.debug("Error when trying to read BLOB: ", ex);
        } catch (DatastoreException e) {
            log.debug("Error when trying to read BLOB: ", e);
        }
        return null;
    }


No comments:

Post a Comment

Please comment here