使用Java在Data Base中插入图像

时间:2011-09-19 13:48:23

标签: java mysql

我需要插入一行Blob列,这是从本地硬盘驱动器中的URL获取的图像。我的尝试是:

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();
}

然后我构建我的Image对象:Imagen ima = new Imagen(0,data,new Date());然后我把它发给另一位经理。我将byte []转换为BLOB对象,如下所示:

    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);

我可以毫无问题地运行它,但我只得到这样的东西“com.mysql.jdbc.Blob@1e1962d”,我的MySQL没有显示我的任何其他东西。

任何人都可以帮助我吗?我使用SQLyog来查看它。

谢谢!

3 个答案:

答案 0 :(得分:2)

好的,你可以使用预备声明:

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

<强>更新

Blob的默认toString()将被调用,这就是为什么你会看到如此奇怪的输出,唯一的方法是使用PreparedStatements,如果我要拧任何人,请纠正我。

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);
    }
}

你有一个连接对象,这次我可以跳过BBDD。

答案 1 :(得分:1)

SQL工具只知道fileds中使用的类型。 SQL工具无法理解blob或类似的二进制字段,只是通过而无需更改。您需要将此二进制数据读入另一个了解数据含义的工具。

答案 2 :(得分:0)

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();
    }

}