我正在尝试将图像添加到mysql数据库的BLOB字段中。图片的大小将小于100kb。但是,我遇到了问题,想知道将这种数据添加到数据库的更好方法是什么?
com.mysql.jdbc.MysqlDataTruncation:数据截断:第1行的“Data”列的数据太长
PreparedStatement addImage = conn.prepareStatement("INSERT INTO Images (Width, Height, Data) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS);
下面是我用来将图像添加到数据库中的方法。
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
将数据字段类型更改为Mediumblob并尝试将140kb图像文件放入数据库后,我收到了另一个错误。
com.mysql.jdbc.PacketTooBigException:查询数据包太大
问题是我尝试将数据添加到数据库的方式。我应该采取其他方法吗?如果是这样的话?
最佳答案
尝试使用MEDIUMBLOB
而不是BLOB
。 BLOB
限制为64KB,而MEDIUMBLOB
列可以容纳16MB。
请参阅this page的“字符串类型的存储要求”部分。
关于java - 使用Java将图像添加到数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/624337/