-1

I have inserted one image file in a table using a java program.I have written the program here. But when i do a select operation on the row i inserted it is displaying non-human readable contents. Instead i want some useful information(file name for example) to be displayed. I am using MySQL by the way. Any help much appreciated.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.FileInputStream;

public class BlobInsertClass {

    static Connection con;
    static PreparedStatement pst;

    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = new ConnectionClass().getConnection();
            File file = new File(
                    "/home/parasuraman/Pictures/lotr-eye-of-sauron-1.png");
            InputStream is = new FileInputStream(file);
            pst = con.prepareStatement("insert into Image values(?,?)");
            pst.setInt(1, 1);
            pst.setBinaryStream(2, is, 15000);
            pst.executeUpdate();
            pst.close();
            con.close();
        } catch (ClassNotFoundException cne) {
            System.out.println("CNE " + cne);
        } catch (SQLException se) {
            System.out.println("SQl " + se);
        } catch (FileNotFoundException fe) {
            System.out.println("FE " + fe);
        }
    }
}
Tiny Rick
  • 284
  • 3
  • 19
  • maybe you could convert the image to a Base64 String and save it in the database along the name and other stuff you may need. Relevant: http://stackoverflow.com/questions/10226046/java-convert-image-to-base64 – Nagarz Jun 17 '15 at 11:04
  • thanks Nagarz. I will try the one you suggested. – Tiny Rick Jun 17 '15 at 11:11

1 Answers1

0

Blob will contain only content of this file (raw data) and no other information (especially no file name). So such information should be stored in some other way (for example as other fields of that table). In your code it would be something like:

pst = con.prepareStatement("insert into Image values(?,?,?)");
pst.setInt(1, 1);
pst.setBinaryStream(2, is, 15000);
pst.setString(3, file.getName());
  • Thanks a lot kosmaty. Even if i have the file name in a separate column if i do a (select * from table) query i would still see the non-readable (raw) content from the second column. So is there no way to get rid of that? – Tiny Rick Jun 17 '15 at 11:16
  • If you do `select *` it will always be there. But you can specify columns in selct clause, e.g. `select id, file_name from table`. – Krzysztof Kosmatka Jun 17 '15 at 12:12