0

I want the Blob field in my database take NULL when I don't have any image to upload. I am using JAVA - Software Netbeans. My database : MySQL

This is my code:

String s; //The path of the image

 InputStream is = new FileInputStream(new File(s));
 preparedStmt.setBinaryStream(24,is,(int)s.length());
Adiva
  • 13
  • 3

1 Answers1

0

You have basically two options, one is to not mention and set the column for the image. This also minimizes the statement and allows database defaults to be used.

The other option is to explicitly set the column binding to null like this:

File f = new File(...);
If (f.exists()) {
    try (InputStream is = new FileInputStream(f);) {
        preparedStmt.setBinaryStream(24,is,f.length());
    }
} else
    preparedStmt.setNull(24, java.sql.Types.BLOB);

The type is a bit tricky, some drivers ignore it or accept a wide range, some are picky. For example PostgreSQL does not like BLOB on a bytea column. I think for MySQL a BLOB or even VARCHAR works.

eckes
  • 10,103
  • 1
  • 59
  • 71
  • Thank you for your answer. But it didn't work for both options. When I upload an image, the field in my database takes NULL and want : When I upload an image the field take BLOB and when I dion't it will take NULL. Any idea please !! Thanks – Adiva Jan 31 '19 at 14:37
  • Not sure I understand what you are asking @advia. Can you add examples, concrete steps and error messages as well as expected and observed results to your original question than we can have a look. – eckes Jan 31 '19 at 19:29
  • I added the If exist if. Your original code used the wrong length for the binary stream (Name length). You can either use file#length or remove the parameter. – eckes Feb 01 '19 at 08:27
  • Thank you for the answer . I tried this solution but didn't work either. Let me explain my question a little bit more : I create an application to book meeting rooms . All the association, entreprise.. send us their planning and other documents. So we need to upload those documents and images to our database and save them. Sometimes the entreprise doesn't have a detailed programs So we didn't need to upload anything. So How can set NULL value to an not uploaded image and set BLOB to an uploaded image ? Thank you again – Adiva Feb 07 '19 at 14:17
  • I appreciate it ! I solved the problem. – Adiva Feb 08 '19 at 14:38