I am trying to insert a photo into a BLOB column of a MySQL table, and I get an exception:
Data too long for column 'logo' at row 1.
Here is the 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();
}
How do I solve this problem?
Use data type LONGBLOB
instead of BLOB
in your database table.
Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.
EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.
Source: Stackoverflow.com