0

I am trying to read a Blob from a MySQL db, containing some random text.

My code looks like this:

Connection conn = DriverManager.getConnection(connection_string);
String message = "Some message";
byte[] messageBytes = message.getBytes("UTF-8");

Blob blob = conn.createBlob();
blob.setBytes(1l,messageBytes);

String sql = "INSERT INTO db.dbname('blob') VALUES ('" + blob + "');"
PreparedStatement pat = conn.prepareStatement(sql);
pat.executeUpdate();

In another class I have the code to read the blob field from database:

//some SQL code to read the blob field here
Blob readBlob = resultSet.getBlob("blob");
byte[] bytes = readBlob.getBytes(1, (int) readBlob.length());
String str = new String(bytes);

System.out.println(str);

The output is: com.mysql.cj.jdbc.Blob@3be81fc2

My code is exactly the same as some of the working solutions on StackOverflow, so I don't know exactly what is wrong.

3
  • 1
    Wouldn't CLOB be more suitable than BLOB, since CLOB is for character data and BLOB is for non-character data. Commented Oct 8, 2020 at 18:12
  • I am gonna try with CLOB too, but then again, I don't see why my code doesn't work. Commented Oct 8, 2020 at 18:14
  • Did you check the value entered into the database after your INSERT (and before you ran the java code that reads from the database)? I mean did you check the value with MySQL Workbench or similar? Also, method executeUpdate() returns a count of the number of rows that were changed. In your case, the method should return 1 (one). Did it? Commented Oct 8, 2020 at 18:27

1 Answer 1

1

Seems like you make a small mistake during insertion. Your code should be something like:

String sql = "INSERT INTO db.dbname('blob') VALUES (?);"
PreparedStatement pat = conn.prepareStatement(sql);
pat.setBlob(1, blob);
pat.executeUpdate();

Please use prepared statements with those placeholders. Otherwise attackers could easily run an SQL injection attack. If you want to see how SQL injection works, there‘s a great Computerphile Video about it on YouTube.

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.