com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'column_name'

2022-09-01 10:12:39

我正在使用Java JDBC和MySQL,我得到这个错误:

com.mysql.jdbc.MysqlDataTruncation: Data truncation: 
Data too long for column 'column_name'

如何纠正此错误?


答案 1

当我打算在数据库中以字节形式插入图像文件时,我在Spring Boot Data JPA应用程序中遇到了同样的问题 - 它给了我同样的错误。

经过多次研发,我找到了如下解决方案。


我在文件中添加了以下行,它解决了问题:application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/conweb?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false

希望它对某人有所帮助。


答案 2

如何在MySQL终端中重现此错误

mysql> create table penguins(val CHAR(2));
Query OK, 0 rows affected (0.08 sec)

mysql> insert into penguins values("AB");
Query OK, 1 row affected (0.00 sec)

mysql> insert into penguins values("ABC");
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'val' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

这是您收到的错误,但是在MySQL终端中将其显示为警告,并且仍然插入您的行,只是静默地截断它。

MySQL JDBC不那么宽容,并且吐出一个硬错误并且不会插入行。


2 解决方案

增加要插入的数据类型的容量,或减小要放置在其中的内容的大小

增加列大小的图例:

If you are using   then use this
-----------------  --------------
smallint           int
int                long
TEXT               LONGTEXT
LONGTEXT           CLOB
CLOB               Store the content to disk, and save the filename in the db.

推荐