Get BLOB from database, how to put them back

2019-09-17 21:34发布

问题:

I got the BLOB data from the database and use the below code to put it into a string(rs is the ResultSet, file is a Map), is there a way to put this string value back to the BLOB columns?

                    Blob blob = rs.getBlob("FILE_DATA");
                    if(blob != null) {
                        byte[] bdata = blob.getBytes(1, (int) blob.length());
                        String data = new String(bdata);
                        file.put("FILE_DATA", data);
                    }

I have tried some suggestions like this one, but they don't work well.

            Blob blbVal = getConnection().createBlob();
            byte[] fileData = value.toString().getBytes();
            blbVal.setBytes(1, fileData);
            cs.setBlob(index, blbVal);

回答1:

I found out that the way I put the BLOB into the String is also not correct, if we don't encode the BLOB data, it will be lost.

Here I found another post which solved this issue perfectly. Thanks for BalusC's answer How to represent an image from database in JSON