I have picture 'osta.jpg' on my desktop and I want to add this to my database Oracle SQL and then load this picture from database in Java application (JDBC) and show on label by a JLabel lblFilm = new JLabel(new ImageIcon( "picture_from_SQL")
(Swing library)
I try adding image to database:
ALTER TABLE film ADD bfile_loc bfile, bfile_type varchar2(4);
UPDATE film SET bfile_type = 'JPEG';
UPDATE film SET bfile_loc = bfilename('GIF_FILES','C:\Users\Maciej\Desktop\osta.jpg') WHERE kategoria IN 'thriller';
However, I don't know how load it in the Java application.
First things first, in order to create a valid BFILE you need to specify an Oracle directory and then the location of the file within that directory. I don't know what your
GIF_FILES
directory is, but if it were created usingthen you would use the following to set the BFILE:
Secondly, in order to read the BFILE out of Oracle using JDBC, you need to use some Oracle-specific classes. Firstly, you need to cast the ResultSet to
oracle.jdbc.OracleResultSet
, so you can use thegetBFILE()
method to get the BFILE locator from the ResultSet. Then open the BFILE, get an InputStream from the BFILE'sbinaryStreamValue()
method and read the data out of that.Here's some example code (error handling could be improved):
In the code above, I also fetch the length of the file, which isn't essential but it will fail if the file cannot be found.
Thirdly, you need to convert the InputStream to an ImageIcon. The ImageIcon class has a constructor that takes a byte array, and you can use answers to this question to convert the InputStream into a byte array.