Skip to content
Advertisement

Retrieving pictures from MySQL using Java

I have a question related to retrieving files from MySQL using JDBC. I managed to save a .png file from my desktop & retrieve it successfully, but I can’t read the file. It shows that the format is unsupported (eventhough I can open the original file without any issue).

Here’s the code:

    PreparedStatement ps = con.prepareStatement("select * from project where files IS NOT NULL ");


    ResultSet rs = ps.executeQuery();
    rs.next();

    Clob c = rs.getClob(3);
    Reader r = c.getCharacterStream();


    FileWriter fw = new FileWriter("C:\Users\xxxl\Pictures\Picture1.png");
    int in;
    while ((in = r.read())!=-1)
        fw.write((char)in);

    fw.close();
    con.close();

    System.out.println("File successfully retrieved");

Any ideas what could be the cause and how to fix it?

Advertisement

Answer

You have to use FileOutpuStream, because you have to write bytes not char. Also you column should be a blob.

Something like this should work

PreparedStatement ps = con.prepareStatement("select * from project where files IS NOT NULL ");


ResultSet rs = ps.executeQuery();
rs.next();

Blob c = rs.getBlob(3);
InputStream r = c.getBinaryStream();


FileOutputStream fw = new FileOutputStream ("C:\Users\xxxl\Pictures\Picture1.png");
int in;
byte[] readBytes = new byte[500];
while (r.read(readBytes)!=-1) {
    fw.write(readBytes);
}
fw.close();
con.close();

System.out.println("File successfully retrieved");

Imports are:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement