使用Java将图像添加到数据库 [英] Adding Image to a database in Java
问题描述
我正在尝试将图像添加到mysql数据库的BLOB字段中.图片的大小将小于100kb.但是,我遇到了问题,想知道将数据添加到数据库的更好方法是什么?
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:数据截断:第1行的"Data"列的数据太长
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);
}
将数据字段类型更改为Mediumblob并尝试将140kb图像文件放入数据库后,我收到了另一个错误.
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:查询数据包太大
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?
推荐答案
尝试使用MEDIUMBLOB
而不是BLOB
. BLOB
限制为64KB,而MEDIUMBLOB
列可以容纳16MB.
Try using a MEDIUMBLOB
instead of a BLOB
. BLOB
is limited to 64KB whereas a MEDIUMBLOB
column can hold 16MB.
请参见此页面.
这篇关于使用Java将图像添加到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!