3

I'm writing a String into a database which has a field of type TEXT. This means I can write 65,535 bytes into that field. After that I will get a SQL Exception:

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'DETAILS' at row 1

So my question is now, how can I check my String and then also how can I cut the String at the correct position that it still fits into the database.

I know it depends also on the encoding. I just saw that the MySQL schema uses the "latin1 - default collection" charset.

Philipp
  • 4,645
  • 3
  • 47
  • 80

2 Answers2

1

I think I got it with this code:

public String cutStringForTEXT(String string) {
    String ENCODING = "ISO-8859-1";
    int FIELD_SIZE = 65535;
    try {
        byte[] bytes = string.getBytes(ENCODING);
        if (bytes.length >= FIELD_SIZE) {
            return new String(Arrays.copyOfRange(bytes, 0, FIELD_SIZE), ENCODING);
        }
    } catch (UnsupportedEncodingException ex) {
    }
    return string;
}

If it's too long, then I get the subset of the array of bytes and convert it back into a String.

Philipp
  • 4,645
  • 3
  • 47
  • 80
0

Of you are using php to insert the value in your database, you can let php check the size of the variable before you insert it into the database. If the variable is too long, you can let it chop off the part that exceeds the size limit.

Xandervr
  • 74
  • 5