我试图将照片插入 MySQL 表的 BLOB 列,但出现异常:
Data too long for column 'logo' at row 1.
这是 JDBC:
int idRestaurant = 42;
String restoname= "test";
String restostatus= "test";
InputStream fileContent = getUploadedFile();
int fileSize = getUploadedFileSize();
Class.forName("com.mysql.jdbc.Driver");
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/resto" , "root" , "" )) {
PreparedStatement ps = conn.prepareStatement("insert into restaurants (idRestaurant, restaurantName, status, logo) values(?,?,?,?)");
ps.setInt(1, idRestaurant);
ps.setString(2, restoname);
ps.setString(3, restostatus);
ps.setBinaryStream(4, fileContent, fileSize);
ps.executeUpdate();
conn.commit();
}
如何解决这个问题?
您正在尝试插入大于列
logo
允许的数据。
根据您的需要使用以下数据类型
TINYBLOB : maximum length of 255 bytes
BLOB : maximum length of 65,535 bytes
MEDIUMBLOB : maximum length of 16,777,215 bytes
LONGBLOB : maximum length of 4,294,967,295 bytes
使用
LONGBLOB
来避免此异常。
在数据库表中使用数据类型
LONGBLOB
而不是 BLOB
。
以下解决方案对我有用。连接到数据库时,指定如果数据太长则应截断数据(jdbcCompliantTruncation)。我的链接如下所示:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
如果增加字符串的大小,如果您尝试存储到数据库中的字符串比新的大小长,您将来可能会遇到同样的问题。
编辑:STRICT_TRANS_TABLES也必须从sql_mode中删除。
String应该用于短文本。默认情况下,它是一个
VARCHAR(255)
解决方案: 在实体中使用带有长度的注释@Column。
示例:
@Entity
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
//..
@Column(length = 1000) //1000 will be fine
private String imgProfile;
}
@Entity
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
//..
@Column(name = "img_profile", columnDefinition="LONGBLOB")
private String imgProfile;
}