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?
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.
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).
Try setBlob instead of setBytes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With