Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Image to a database in Java

Tags:

java

mysql

jdbc

I am trying to add an image to a BLOB field in a mysql database. The image is going to be less then 100kb in size. However I am running into problems and was wondering what would be a better way to add this data to the database?

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'Data' at row 1

PreparedStatement addImage = conn.prepareStatement("INSERT INTO Images (Width, Height, Data) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS);

Below is the method that I am using to add the image into the database.

public int addImage(Image image) throws SQLException, IllegalArgumentException
{
    this.addImage.clearParameters();
    byte[] imageData = ImageConverter.convertToBytes(image);
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    if (width == -1 || height == -1)
    {
        throw new IllegalArgumentException("You must load the image first.");
    }



    this.addImage.setInt(1, width);
    this.addImage.setInt(2, height);
    this.addImage.setBytes(3, imageData);
    this.addImage.executeUpdate();

    ResultSet rs = this.addImage.getGeneratedKeys();
    rs.next();

    return rs.getInt(1);
}

SQL Definition for the table

After Changing the datafield type to a Mediumblob and attempting to place a 140kb image file into the database i received a different error.

com.mysql.jdbc.PacketTooBigException: Packet for query is too large

Is the problem the way in which i am trying to add the data to the database. Should I take a different approach? If so which way?

like image 866
Malachi Avatar asked Mar 08 '09 21:03

Malachi


3 Answers

Try using a MEDIUMBLOB instead of a BLOB. BLOB is limited to 64KB whereas a MEDIUMBLOB column can hold 16MB.

See the 'Storage Requirements for String Types' section of this page.

like image 137
Luke Woodward Avatar answered Oct 07 '22 11:10

Luke Woodward


To deal with PacketTooBigException, it looks like you need to tweak a config variable, max_allowed_packet. See http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html . However, by default MySQL 5.1 should give you no problems with up to 1MB . What version of MySQL are you using (both server and client).

like image 26
Matthew Flaschen Avatar answered Oct 07 '22 10:10

Matthew Flaschen


Try setBlob instead of setBytes

like image 25
Maurice Perry Avatar answered Oct 07 '22 11:10

Maurice Perry