简体   繁体   中英

Split the string 3 times and inserted into database - Java

Its scraping tool, while running getting more length of string value like 152263 . I want to insert this string value into the db (SQL - nvarchar(max)) the entire length not fit in a single column ( after 42600 its truncated ), so i alter the table adding one more columns and insert the value.

 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, "");
 }

the above one working perfectly for 2 columns. some cases its exit more than two column let me know how can i split into 3 times (equal to string length) and stored into 3 columns in sql db.

    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, "");
    }

Check length against a given limit and compare from longest to shortest range. Not sure if you want to store "" or NULL in empty columns

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);

This is a solution using a loop to make a flexible count of colums:

    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);

(not tested)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM