我试图将照片插入MySQL表的BLOB列,我得到一个例外:
Data too long for column 'logo' at row 1.
Run Code Online (Sandbox Code Playgroud)
这是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();
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
Ani*_*rni 80
您正在尝试插入大于列允许的数据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
Run Code Online (Sandbox Code Playgroud)
使用LONGBLOB以避免此异常.
以下解决方案为我工作.连接到db时,如果数据太长(jdbcCompliantTruncation),请指定应截断数据.我的链接看起来像这样:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
Run Code Online (Sandbox Code Playgroud)
如果增加字符串的大小,如果您尝试存储到数据库中的字符串长于新大小,则将来可能会遇到同样的问题.
编辑:STRICT_TRANS_TABLES也必须从sql_mode中删除.