将字符串拆分3次并插入数据库-Java

时间:2018-08-23 07:40:21

标签: java

它的抓取工具,在运行时会获得更长的字符串值长度,例如152263。 我想将此字符串值插入数据库(SQL-nvarchar(max)) 整个长度无法容纳在单列(after 42600 its truncated)中,因此我更改了表,增加了另外一列并插入值。

 if (fullText.length() > 42600) {
     preparedStatement.setString(35, fullText.substring(0, 42500));
     preparedStatement.setString(36, fullText.substring(42500, fullText.length()));
 } else {
     preparedStatement.setString(35, fullText);
     preparedStatement.setString(36, "");
 }

上面的一个完美地适用于2列。 在某些情况下,其出口超过两列 让我知道如何将它分成3倍(等于字符串长度)并存储到sql db中的3列中。

3 个答案:

答案 0 :(得分:0)

    if (fullText.length() > 42600) {
        preparedStatement.setString(35, fullText.substring(0, 42500));
        if (fullText.length() > 85000) {
            preparedStatement.setString(36, fullText.substring(42500, 85000));
            preparedStatement.setString(37, fullText.substring(85000, fullText.length()));
        } else {
            preparedStatement.setString(36, fullText.substring(42500, fullText.length()));
        }
    } else {
        preparedStatement.setString(35, fullText);
        preparedStatement.setString(36, "");
        preparedStatement.setString(37, "");
    }

答案 1 :(得分:0)

根据给定的限制检查长度,并比较最长和最短范围。不确定是否要在空列中存储“”或NULL

String first = "";
String middle = "";
String last = "";

if (fullText.length > SPLIT_LIMIT * 2) {
    last = fullText.substring(SPLIT_LIMIT * 2 + 1);
}

if (fullText.length > SPLIT_LIMIT) {
    middle = fullText.substring(SPLIT_LIMIT + 1, SPLIT_LIMIT * 2);
    first = fullText.substring(0, SPLIT_LIMIT * 2);
} else {
    first = fullText;
}

preparedStatement.setString(35, first);
preparedStatement.setString(36, middle);
preparedStatement.setString(37, last);

答案 2 :(得分:0)

这是一个使用循环来灵活计算列数的解决方案:

    String text = "";
    int idCounter = 35;
    while(text.length() > 42600){
        preparedStatement.setString(idCounter, text.substring(0, 42600));
        text = text.substring(42601,text.length());
        idCounter++;
    }
    preparedStatement.setString(idCounter, text);

(未经测试)

相关问题