MySQL数据截断错误

时间:2020-03-05 18:56:10  来源:igfitidea点击:

我正在使用Java应用程序中的一个相当简单的数据库。我们正在尝试使用标准JDBC mysql适配器一次插入约200k文本。我们间歇性地得到com.mysql.jdbc.MysqlDataTruncation:数据截断:数据太长而导致列错误。

列类型为longtext,数据库排序规则为UTF-8. 使用MyISAM和InnoDB表引擎都会显示该错误。客户端和服务器端的最大数据包大小均设置为1 GB,因此也不应该引起问题。

解决方案

回答

那么,我们可以通过执行INSERT IGNORE来使其忽略该错误,该操作只会截断数据并以任何方式插入。 (来自http://dev.mysql.com/doc/refman/5.0/en/insert.html)

If you use the IGNORE keyword, errors
  that occur while executing the INSERT
  statement are treated as warnings
  instead. For example, without IGNORE,
  a row that duplicates an existing
  UNIQUE index or PRIMARY KEY value in
  the table causes a duplicate-key error
  and the statement is aborted. With
  IGNORE, the row still is not inserted,
  but no error is issued. Data
  conversions that would trigger errors
  abort the statement if IGNORE is not
  specified. With IGNORE, invalid values
  are adjusted to the closest values and
  inserted; warnings are produced but
  the statement does not abort.

回答

在我看来,我们正在尝试将太多字节放入一列中。由于代码中的错误,昨晚我在MySQL上遇到了一个非常类似的错误。我本来打算

foo.status = 'inactive'

但实际上已经打过

foo.state = 'inactive'

其中foo.state应该是美国状态的两个字符代码(varchar(2))。我和你有同样的错误。我们可能会在代码中寻找类似的情况。

回答

检查UTF-8数据是否全部为3字节Unicode。如果我们有4个字节的字符(在Unicode和Java中为合法字符,在MySQL 5中为非法字符),则在尝试插入它们时会抛出此错误。这个问题应该在MySQL 6.0中解决。

回答

我刚刚遇到了这个问题,并通过删除文本中的所有非标准ascii字符解决了此问题(遵循上面的UTF-8建议)。

我在Debian 4,Java 5系统上遇到了问题;但是相同的代码在Ubuntu 9.04,Java 6上也能正常工作。两者都运行MySql 5.