Sierra
Sierra

Reputation: 313

Insert a image in Data Base using Java

I need to insert a row with a Blob column which is an image got from an URL in my local hard drive. My try is:

File file = new File(imageURL);
FileInputStream input;
byte[] data = null;
try {
    input = new FileInputStream(file);
    data = new byte[input.available()];
    input.close();
} catch (Exception e) {
    e.printStackTrace();
}

Then I build my Image object: Imagen ima = new Imagen(0, data, new Date()); and I send it into another manager. I get converted the byte[] into a BLOB object like this:

    byte[] datos = image.getDatos();
    Blob blob = null;
    try {
        blob = conection.createBlob();
        blob.setBytes(1,datos);
    } catch (SQLException e) {          
        e.printStackTrace();
    }

    java.sql.Date sqlDate = new java.sql.Date(image.getFecha().getTime());

    String query = " INSERT INTO imagen VALUES('" + image.getId() + "','"
            + blob + "','" + sqlDate + "') ";

    int lastID = BBDD.add(query, conection);

I can run this without problems but I only get something like this "com.mysql.jdbc.Blob@1e1962d" and my MySQL doesn´t show my anything else.

Could anyone help me?. I use SQLyog to see it.

Thank you!!

Upvotes: 1

Views: 6066

Answers (3)

Vicky
Vicky

Reputation: 9585

package com.technicalkeeda;

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

public class InsertImageTest {

    /**
     * This is used to get the Connection
     * 
     * @return
     */
    public Connection getConnection() {
        Connection connection = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/technicalkeeda", "root", "");
        } catch (Exception e) {
            System.out.println("Error Occured While Getting the Connection: - "
                    + e);
        }
        return connection;
    }

    /**
     * Insert Image
     */
    public void insertImage() {
        Connection connection = null;
        PreparedStatement statement = null;
        FileInputStream inputStream = null;

        try {
            File image = new File("C:/honda.jpg");
            inputStream = new FileInputStream(image);
            connection = getConnection();
            statement = connection
                    .prepareStatement("insert into trn_imgs(img_title, img_data) "
                            + "values(?,?)");
            statement.setString(1, "Honda Car");
            statement.setBinaryStream(2, (InputStream) inputStream,
                    (int) (image.length()));

            statement.executeUpdate();
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException: - " + e);
        } catch (SQLException e) {
            System.out.println("SQLException: - " + e);
        } finally {
            try {
                connection.close();
                statement.close();
            } catch (SQLException e) {
                System.out.println("SQLException Finally: - " + e);
            }
        }

    }

    /***
     * Execute Program
     * 
     * @param args
     * @throws SQLException
     */
    public static void main(String[] args) throws SQLException {
        InsertImageTest imageTest = new InsertImageTest();
        imageTest.insertImage();
    }

}

Upvotes: 0

Peter Pan
Peter Pan

Reputation: 31

Ok you can use prepared statement :

java.sql.PreparedStatement ps =  
                        connection.prepareStatement("UPDATE table SET file = ?");
 ps.setBinaryStream(1, new FileInputStream(file), (int)file.length());

UPDATE

The Blobs default toString() will be called which is why you are seeing such weird output, the only way would be to use PreparedStatements, please correct me if i am wring anyone.

public void insert() throws Exception {
    Connection conn = null;
    PreparedStatement ps = null;

    InputStream is = null;
    try {
        conn = this.connection.getConnection();
        String sql = "INSERT INTO Table (image) VALUES (?)";

        ps = conn.prepareStatement(sql);
        if (this.file != null && this.file.canRead()) {
            is = new BufferedInputStream(new FileInputStream(this.file));
            ps.setBinaryStream(1, is, (int) this.file.length());
        } else {
            ps.setNull(1, Types.BLOB);
        }
    } catch (Exception e) {
        LOG.error("", e);
        throw e;
    } finally {
        FileUtil.close(is);
        DAOUtil.close(conn);
    }
}

And you have a connection object, you can skip BBDD this time i propose.

Upvotes: 3

mmmmmm
mmmmmm

Reputation: 32651

SQL tools only know about the types used in the fileds. A blob or similar binary field is not understood by the SQL tools and is just passed through without alteration. You will need to read this binary data into another tool that understands what the data means.

Upvotes: 1

Related Questions