13
  1. How to create BLOB object in Java?
  2. How to set the BLOB value from DB?
  3. How to set the BLOB value in DB?

I have create the BLOB object like this:

byte [] fileId = b.toByteArray();
Blob blob = new SerialBlob(fileId);

But it gives me an error.

3
  • Why do you need to create a BLOB object ? Or do you want to read the BLOB data from the DB ? Commented Jun 26, 2013 at 5:36
  • I am fetching a BLOB value from db and I want to save this value in BLOB object that's why I want to create a object.After save again I want to save this value in another db that time I want to get that value.I am using spring framework. Commented Jun 26, 2013 at 5:44
  • possible duplicate of Insert BLOB using java for both DB2 and Oracle Commented Jun 26, 2013 at 6:53

1 Answer 1

24
  1. to create BLOB use Connection.createBlob

  2. to write BLOB to DB use PreparedStatement.setBlob

  3. to read BLOB from DB use ResultSet.getBlob

Assuming you have table t1 with BLOB column b1:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Blob b1 = conn.createBlob();
b1.setBytes(1, new byte[10]); // first position is 1. Otherwise you get: Value of offset/position/start should be in the range [1, len] where len is length of Large Object[LOB]

PreparedStatement ps = conn.prepareStatement("update t1 set c1 = ?");
ps.setBlob(1, b1);
ps.executeUpdate();

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select c1 from t1");
Blob b2 = rs.getBlob(1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.